【发布时间】:2018-08-14 09:07:29
【问题描述】:
我有下一个方法:
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)时的这个需要
【问题讨论】:
-
是python将错误打印回java,而不是java抛出异常,对吧?
-
你说得对@phflack。但是,如果我在终端中运行相等的字符串,则一切正常
-
如果将行更改为
python -c \"print('test')\"会发生什么?奇怪的是空间会是一个问题 -
@phflack 空结果)
-
尝试让它在一个.bat文件中工作并从java中执行,它会少一些麻烦
标签: java python macos terminal