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了。

相关文章

这篇文章主要介绍了idea中mapper快速跳转到xml插件的方法,具...
今天小编给大家分享的是IDEA搭建Maven模块化项目的实现方法,...
这篇文章主要介绍了ideaintellij怎么快速修复if语句缺少大括...
这篇文章主要介绍“idea运行main方法或Test避免编译整个应用...
这篇文章主要介绍“idea项目全局去掉严格的语法校验方式是什...
本文小编为大家详细介绍“Windows、IDEA、VSCode常用快捷键有...