Doc: 利用ProcessBuilder.start()
和Runtime.exec
方法建立本機進程並返回一個可用於控制該進程並獲取有關該進程信息的進程子類實例。經過方法getOutputStream
,getInputStream'和
getErrorStream`獲取進程的輸出流。java
無參數Python腳本:python
# -*- coding: utf-8 -*- def Non_agr_func: print("java use python script")
java程序調用:shell
//調用過程可能出現IOException,須要處理異常 String cmd = "python C:\\Users\\Non_arg_func.py"; Process process = Runtime.getRuntime().exec(cmd); BufferedReader stream = new BufferedReader(new InputStreamReader(process.getInputStream())); BufferedReader errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream())); String contentLine; String errorLine; while ((contentLine = stream.readLine()) != null) { System.out.print("content:"contentLine); } while ((errorLine = errorStream.readLine()) != null) { System.out.print("error:"errorLine); } stream.close();
傳參Python腳本服務器
# -*- coding: utf-8 -*- import sys def args_func(a, b): return a+b if __name__ = '__main__': args = [] for i in rang(1, len(sys.argv)): args.append(int(sys.argv[i])) print(args_func(args[0], args[1])) # sys.argv[0]表明python程序名,因此列表從1開始讀取參數
java程序調用:app
//與無參Python腳本調用徹底一致,只須要在命令中傳入須要的參數 //下面兩種命令的寫法均可以 String command = String.format("python %s %s %s", "C:\\Users\\arg_func.py", "1", "2"); String[] args = new String[] {"python", "C:\\Users\\arg_func.py", "1", "2"}; Process process = Runtime.getRuntime().exec(cmd); BufferedReader stream = new BufferedReader(new InputStreamReader(process.getInputStream())); String contentLine; while ((contentLine = stream.readLine()) != null) { System.out.print("content:"contentLine); }
服務部署文檔requirement.txtide
程序終究是須要部署到服務器上的,而部署過程就須要引入咱們的Python中用到的模塊,所以須要添加一個requirement.txt
文檔,用於一鍵引入須要的模塊。這裏咱們使用pipreqs工具來自動生成該文件工具
安裝ui
pip install pipreqs
用法編碼
#跟目錄下使用命令 pipreqs ./
報錯code
# Windows下報編碼錯誤 UnicodeDecodeError: 'gbk' codec can't decode byte 0xa8 in position 24: illegal multibyte sequence # 解決方法:指定編碼 pipreqs ./ --encoding=utf8