java 直接調用python指令碼,並傳遞參數

來源:互聯網
上載者:User


最近陸續用python寫了很多檔案處理指令碼,雖然功能都比較簡單 ,但還是感覺到python對檔案處理的簡潔高效 ,越發覺得java的文法相當的繁瑣~


接到個需求處理ftp資料介面 。所以想把python指令碼也用上。java代碼定時掃描ftp資料倉儲 ,調用python指令碼入庫。



直接採用java執行系統命令的方式

@Asyncpublic 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]表示要執行的是python 指令碼 ,args[1] 指令檔的全路徑

該方法調用 AbstractReadFileLine.class 檔案路徑下的 PythonFileHandle.py 指令碼 ,並傳入String數群組類型的參數(需要處理的檔案全路徑)

PythonFileHandle指令碼接受java傳入的檔案路徑參數(數組),解析併入庫

PythonFileHandle.py 代碼

import pymssql,time,sysreload(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] 儲存的是py檔案自身的路徑,故接受參數從sys.argv[1]開始。



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.