英文:
Failed to run Python script from Java using Intellij
问题
我正在尝试在Intellij IDEA中使用Java代码运行Python脚本:
String commandString = "python /home/.../mypythonscript.py arg1 arg2";
try {
Process process = Runtime.getRuntime().exec(commandString);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
} catch(IOException e) {
System.out.println(e.getMessage());
}
这个Python脚本会输出一个字符串,在我从Ubuntu Linux终端运行时效果很好。然而,使用上述Java代码运行Python脚本会返回一个错误消息:
Failed to run Python Script: Cannot run program "python": error=2, No such file or directory.
文件路径是正确的(我在终端中运行Python脚本时使用的路径和参数与之前相同),而且我已经将脚本权限设置为777。在Intellij中,我还进入了“文件>设置>外观与行为>路径变量”,并添加了一个包含Python脚本的文件夹的路径(它位于Pycharm项目的文件夹中)。然而,我仍然在收到这个错误消息。
非常感谢您的帮助!
英文:
I'm attempting to run a Python script using Java code in Intellij IDEA:
String commandString = "python /home/.../mypythonscript.py arg1 arg2";
try {
Process process = Runtime.getRuntime().exec(commandString);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
} catch(IOException e) {
System.out.println(e.getMessage());
The Python script outputs a single String, and works great when I run it from my Ubuntu Linux terminal. However, using the above Java to run the Python script returns an error message:
> Failed to run Python Script: Cannot run program "python": error=2, No such file or directory.
The file path is correct (the path and arguments I give are identical to what I used to run the Python script in the terminal), and I've set the script permissions to 777. In Intellij, I've also gone to File>Settings>Appearance & Behavior>Path Variables and added a path to the folder that contains the Python script (it's being held in a folder for Pycharm projects). However, I'm still getting the error.
Any help would be much appreciated!
答案1
得分: 0
我这位经验丰富的Java开发朋友没有账号,但他找出了问题,我会在这里发布解决方案,以供将来遇到类似问题的人参考:
脚本是用Python3编写的,但我使用的代码:
String commandString = "python /home/.../mypythonscript.py arg1 arg2";
是针对Python 2的。应该改为:
String commandString = "python3 /home/.../mypythonscript.py arg1 arg2";
英文:
A more experienced Java developer friend of mine who doesn't have an account figured out the problem, the solution to which I'm posting here for anyone encountering a similar issue in the future:
The script was written in Python3, but the code I used:
String commandString = "python /home/.../mypythonscript.py arg1 arg2";
is for Python 2. It should have been written:
String commandString = "python3 /home/.../mypythonscript.py arg1 arg2";
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论