现象描述
我在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了。