以下代碼想通過測試,必須有一個前提:電腦上安裝了Python環境。不太習慣說廢話,直接上代碼了。
以下是用于測試的python代碼(mytest.py):
# 因為用戶到了參數處理,所以需要引用
import argparsedef test(uname, msg):return uname + ',你好,你發來的消息是:' + msgdef main():parser = argparse.ArgumentParser(description="調用測試")# 此處uname的命名,在調用時會用到parser.add_argument("--uname", type=str, help="傳入的用戶名")parser.add_argument("--msg", type=str, help="傳入的消息")args = parser.parse_args()result = test(uname=args.uname, msg=args.msg)# 輸出返回值,若有調用,對方可獲取print(result)if __name__ == "__main__":main()
以下是Java代碼:
public void test() {try{// 工作目錄String currentDirectory = System.getProperty("user.dir");// 注意開頭的testPython根據實際情況進行調整,因為我將Python代碼和Java代碼放入到了同一個項目中,所以這么寫String pythonScriptRelativePath = "testPython/src/main/java/com/mytest.py";// py文件的具體路徑String pythonScriptPath = currentDirectory + File.separator + pythonScriptRelativePath;// 執行 Python 腳本,帶有參數ProcessBuilder processBuilder = new ProcessBuilder("python", pythonScriptPath,"--uname", "Vincent Lu", "--msg", "收到消息了嗎?");// 讀取腳本的標準輸出Process process = processBuilder.start();InputStream stdout = process.getInputStream();// 此處,我用了GBK,大家可根據實際情況進行調整BufferedReader reader = new BufferedReader(new InputStreamReader(stdout, "GBK"));String line;while ((line = reader.readLine()) != null) {System.out.println("收到Python的返回值: " + line);}// 若發生錯誤,會執行以下內容InputStream stderr = process.getErrorStream();BufferedReader errorReader = new BufferedReader(new InputStreamReader(stderr));while ((line = errorReader.readLine()) != null) {System.out.println("錯誤內容: " + line);}// 等待進程結束并獲取退出值int exitValue = process.waitFor();System.out.println("Exit value: " + exitValue);} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}}
關于參數,有一點需要注意一下,若Python想接收一個dict類型的參數,在parser.add_argument("--dictData", type=str, help="傳入的dict類型數據,理論上是一個JSON") 配置中,type依舊可以使用str類型,但是,在使用過程中,需要eval轉換一下。如下:
result = test(dictData=eval(args.dictData))
更有趣的是,在JAVA中想傳遞JSON串,我必須得寫成
String speedJson = "{\\\"SPEED\\\":[35, 95, 92, 92, None, 90, 93, 90, None, None, None, None, None, None, None, None, None]}"
我不太明白,為什么要加3個斜杠。
好啦,就到這里吧,我是來自北京天碼科技的盧澤。