如何从java正确运行python?
我有下一个方法:如何从java正确运行python?,java,python,macos,terminal,Java,Python,Macos,Terminal,我有下一个方法: 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 Buffere
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刻录到此目录之前):
当我在java代码中运行此代码时,他返回错误:
File "<string>", line 1
"from
^
SyntaxError: EOL while scanning string literal
文件“”,第1行
“从
^
SyntaxError:扫描字符串文字时下线
我做错了什么
注:我需要运行python方法/类/文件来读取、解析和显示图形数据。但是,当java运行python单一方法(def)时,我发现在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测试|程序
)
主要的缺点是代码旁边会有一个浮动的.bat文件
如果打包到.jar,您可能需要在执行之前先执行您缺少说明python解释器所在位置的shebang语句。它应该是第1行
Runtime.exec已过时。它在很久以前被替换为:
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();
请注意,test import read_and_show;read_and_show()中的
周围没有双引号字符。这些引号是shell使用的东西(如bash
)。python命令从未实际看到它们,也不应该看到它们。从Java(或任何其他语言)执行子进程不调用shell;它直接执行命令。这意味着引号不会被任何shell解释,它们会作为参数的一部分传递给python程序。是python将错误打印回java,而不是java引发异常,对吗?你说得对@phflack。但是如果我在终端中运行相等的字符串,所有工作都会发生正确:如果将行更改为python-c\“print('test'),会发生什么情况\“
?奇怪的是,这个空间将是一个issue@phflack空结果)试着让它在.bat文件中工作,并从java执行,这会少一点麻烦。虽然文件中缺少它,但它如何改变从命令行执行相同命令的行为,而不是从java执行相同命令的行为?我认为在这两种情况下都会失败,或者在这两种情况下都会成功。如果您键入“python”,并从命令行启动python,那么您已经手动找到了解释器。如果您从其他地方运行脚本,您需要告诉脚本解释器在哪里。是的,但看起来它们将所有内容都作为参数传递,而不是作为用户输入
#!/usr/bin/python
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();