IDEA中通過Java調用Python腳本報錯

現象描述

我在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是可以的,一時間感覺很疑惑。

image-20210728150816398

解決方案

查了下,在IDAE中使用運行命令,其實是不能使用系統設置的環境變量的。需要在IDEA中另外設置。

image-20210728151016006

image-20210728151117749

設置完之後再執行就OK了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章