IDEA中通過Java呼叫Python指令碼報錯
阿新 • • 發佈:2021-07-28
現象描述
我在IDEA中除錯一段Java呼叫Python的程式碼,一直報下面的錯誤。
我的程式碼:
public class ScriptTest { public static void main(String[] args) { String result = ""; try { Process process = Runtime.getRuntime().exec("python D:/xxl/my.py test中文" ); InputStreamReader ir = new InputStreamReader(process.getInputStream(),"GBK"); LineNumberReader input = new LineNumberReader(ir); result = input.readLine(); input.close(); ir.close(); // process.waitFor(); } catch (Exception e) { System.out.println("呼叫python指令碼並讀取結果時出錯:" + e.getMessage()); } System.out.println(result); } }
my.py的內容非常簡單,如下:
import sys
if __name__ == "__main__":
filename = sys.argv[1]
print (filename)
當我執行上面的程式碼時,一直報下面的錯誤:
Connected to the target VM, address: '127.0.0.1:25684', transport: 'socket'
呼叫python指令碼並讀取結果時出錯:Cannot run program "python": CreateProcess error=2, 系統找不到指定的檔案。
查了下這個錯誤,是因為找不到Python這個命令。
但是我通過命令列執行python是可以的,一時間感覺很疑惑。
解決方案
查了下,在IDAE中使用執行命令,其實是不能使用系統設定的環境變數的。需要在IDEA中另外設定。
設定完之後再執行就OK了。
人生的主旋律其實是苦難,快樂才是稀缺資源。在困難中尋找快樂,才顯得珍貴~