我有下一个方法:
public void callPython() throws IOException {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("python -c \"from test import read_and_show; read_and_show()\" src/main/python");
BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream()));
BufferedReader bfre = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
String outputStr = "";
while ((outputStr = bfr.readLine()) != null) {
System.out.println(outputStr);
}
while ((outputStr = bfre.readLine()) != null) {
System.out.println(outputStr);
}
}
在python文件中的下一个代码:
import os
from stat import *
def read_and_show():
print('worked!')
当我在终端中调用它时都正常工作(在我cd到这个目录之前):
MacBook-Pro-Nikita-2:python NG$ python -c "from test import read_and_show; read_and_show()"
worked!
当我在我的java代码中运行此代码时,他返回错误:
File "<string>", line 1
"from
^
SyntaxError: EOL while scanning string literal
我做错了什么?
P.S。:我需要运行python方法/类/文件来读取,解析和显示图形数据。但是对于这个需要java运行python的单一方法(def)
从java执行其他程序时,我发现在java中尽可能简单地保持它更容易,而是执行批处理文件
Runtime.getRuntime().exec("chrome.exe www.google.com");
相反会成为
Runtime.getRuntime().exec("openChrome.bat");
和openChrome.bat:
chrome.exe www.google.com
这使得在不重新编译的情况下更容易测试命令,但如果需要将变量作为参数传递,则可能会变得复杂
要使用像echo
和cd
这样的shell内置函数,批处理文件可以创建奇迹(即echo test | program
)
主要的缺点是你的代码旁边会有一个漂浮的.bat文件
如果打包到.jar,您可能需要先执行copy the .bat file out of the .jar
你错过了说明python解释器所在位置的shebang语句。它应该是第1行
#!/usr/bin/python
Runtime.exec已过时。很久以前它被ProcessBuilder class取代:
ProcessBuilder builder = new ProcessBuilder(
"python", "-c", "from test import read_and_show; read_and_show()", "src/main/python");
builder.redirectInput(ProcessBuilder.Redirect.INHERIT);
Process pr = builder.start();
请注意,from test import read_and_show; read_and_show()
周围没有双引号字符。这些引用是shell使用的东西(如bash
)。 python命令从未真正看到它们,也不应该看到它们。从Java(或任何其他语言,实际上)执行子进程不会调用shell;它直接执行命令。这意味着引号不会被任何shell解释,并且它们将作为参数的一部分传递给python程序。