西安微網(wǎng)站制作網(wǎng)上廣告宣傳怎么做
前期準備
1.首先需要在本地環(huán)境中安裝配置python環(huán)境
Python(含PyCharm及配置)下載安裝以及簡單使用(Idea)
博主本次使用python版本為py3.7.3
2.idea安裝python插件
位置:File->Settings->Plugins->python->安裝后重啟即可
3.引入jython依賴
<!--python-->
<dependency><groupId>org.python</groupId><artifactId>jython-standalone</artifactId><version>2.7.0</version>
</dependency>
編寫Java代碼
1.方式1:
String polygon1="yoursParam";try {// 設置Python腳本路徑和參數(shù)String pythonScriptPath = yours.py";// 構建命令String command = "python " + pythonScriptPath + " " + polygon1;try {// 執(zhí)行命令Process process = Runtime.getRuntime().exec(command);// 讀取腳本輸出BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));String line;while ((line = reader.readLine()) != null) {System.out.println(line);}// 等待腳本執(zhí)行完畢process.waitFor();reader.close();} catch (IOException | InterruptedException e) {e.printStackTrace();}
2.方式2:
try {// 創(chuàng)建命令列表List<String> command = new ArrayList<>();command.add("python");command.add(yoursUrl);command.add(yoursParam);// 創(chuàng)建進程生成器并執(zhí)行命令ProcessBuilder pb = new ProcessBuilder(command);Process process = pb.start();// 讀取腳本輸出BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));String output;while ((output = reader.readLine()) != null) {System.out.println(output );}// 等待腳本執(zhí)行完畢process.waitFor();} catch (IOException | InterruptedException e) {e.printStackTrace();}
兩種方式區(qū)別
參數(shù)的形式:
1.Runtime.getRuntime().exec(command)
接受一個字符串形式的命令,例如 “python your_script.py”.
2.ProcessBuilder
接受一個命令的字符串列表,例如 {“python”, “your_script.py”}. 使用列表形式可以更靈活地傳遞參數(shù)和配置。
管理進程的能力:
1.Runtime.getRuntime().exec(command)
返回一個Process
對象,但對于該進程的控制和管理能力有限。
2.ProcessBuilder
返回一個 ProcessBuilder 對象,該對象可以進行更高級的進程控制,例如重定向輸入輸出流、設置環(huán)境變量、設置工作目錄等。
子進程輸出的處理:
1.Runtime.getRuntime().exec(command)
需要手動處理子進程的輸入流和輸出流,否則可能會導致進程阻塞或數(shù)據(jù)丟失。
2.ProcessBuilder
在調(diào)用 start() 方法后,可以通過 Process 對象的getInputStream()、getOutputStream() 和 getErrorStream()
方法來獲取子進程的標準輸入、輸出和錯誤輸出流。
python腳本此處不再展示 可根據(jù)自己情況傳值調(diào)用即可 可通過文件方式傳值 py處用pandas庫中方法讀取xlsx或者txt等都可自行選擇 如若直接傳值可用Processbuilder 命令行獲取參數(shù)即可 py對應方法為sys.argv 基于sys庫