java calls the python script directly and passes the parameter code instance

  • 2021-07-13 05:09:32
  • OfStack

Recently, I have written a lot of file processing scripts with python one after another. Although the functions are relatively simple, I still feel that python is concise and efficient in file processing, and I feel that the syntax of java is quite cumbersome ~

Connect to a demand processing ftp data interface. So I want to use python script as well. The java code scans the ftp data warehouse regularly and calls the python script into the warehouse.

java is directly used to execute system commands


@Async
	public void readFileByPython(List<String> filePaths) throws FileNotFoundException {
		URL localSrcUrl = AbstractReadFileLine.class.getResource("");
		String localSrcPath = localSrcUrl.getPath();
		localSrcPath = localSrcPath.substring(1, localSrcPath.length());
		String pythonFile = localSrcPath + "PythonFileHandle.py";
 
		int size = filePaths.size() + 2;
		String[] args = new String[size];
		args[0] = "python";
		args[1] = pythonFile;
		for(int i =0;i<filePaths.size() ;i++){
			int index = i+2;
			args[index] = filePaths.get(i);
		}
		try {
			
	      System.out.println("start"); 
	      Process proc = Runtime.getRuntime().exec(args);
	      InputStream is = proc.getErrorStream(); 
	      InputStreamReader isr = new InputStreamReader(is); 
	      BufferedReader br = new BufferedReader(isr); 
	      String line = null; 
	      System.out.println("<ERROR>"); 
	      while((line = br.readLine())!=null){ 
	          System.out.println(line); 
	          System.out.println("</ERROR>"); 
	          int exitValue = proc.waitFor(); 
	          System.out.println("Process exitValue="+exitValue); 
	      } 
	      System.out.println("end"); 
	      } catch (Exception e){ 
	      e.printStackTrace(); 
	      } 
	     
	}

String[] args = new String[size];
args [0] = "python"; args [1] = pythonFile; args [0] indicates that the python script is to be executed, and the full path of the args [1] script file

This method calls the PythonFileHandle. py script under the AbstractReadFileLine. class file path and passes in parameters of the String array type (full path of the file to be processed)

The PythonFileHandle script accepts the file path parameter (array) passed in by java, parses it and puts it into storage

PythonFileHandle. py code


import pymssql,time,sys
reload(sys)
sys.setdefaultencoding("utf-8")
class MSSQL:
  def __init__(self,host,user,pwd,db):
    self.host = host
    self.user = user
    self.pwd = pwd
    self.db = db
 
  def __GetConnect(self):
    if not self.db:
      raise(NameError,"")
    self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
    cur = self.conn.cursor()
    if not cur:
      raise(NameError,"")
    else:
      return cur
 
  def ExecQuery(self,sql):
    cur = self.__GetConnect()
    cur.execute(sql)
    resList = cur.fetchall()
 
    #
    self.conn.close()
    return resList
 
  def ExecNonQuery(self,sql):
    cur = self.__GetConnect()
    cur.execute(sql)
    self.conn.commit()
    self.conn.close()
    
def insertToCloseList(data ,ms): 
  sql = "insert into t_isee_closelist_infos (WORK_ORDER_ID,CRM_Cdsc_Id,APPRAISE_TYPE,CRM_Accept_Date,latn_code,theme_row_id,TASK_EXECUTE_ROW_ID,CRM_Accept_REASON,ASSET_INTEG_ID) values ( '" 
  temp ="' , '"
  sqlStr = temp.join(data)
  sql = sql + sqlStr + "')"
  ms.ExecNonQuery(sql)
 
 
 
ms = MSSQL(host="172.30.0.186",user="sa",pwd="",db="test")
fengefu = '$%$'
for i in range(1, len(sys.argv)):
  read = open(sys.argv[i] ,'r')
  for line in read:
    line=line.strip('\n') 
    data = line.split(fengefu)
    insertToCloseList(data,ms)
  read.close

sys. argv [0] stores the path to the py file itself, so the acceptance parameter begins with sys. argv [1].


Related articles: