我正在尝试打印出java内部python中方法的返回值。 这是我的python代码,位于文件file1.py中:
def main():
return(5)
这是我的Java代码:
import java.io.*;
public void sampleMethod(){
try{
System.out.println(Runtime.getRuntime().exec("cmd /c start file1.py main()"));
}
catch (IOException e){
System.out.println("Failed" + e);
}
}
当我跑步时,它返回java.lang.ProcessImpl@12a337b
。每次运行时,@
符号后的所有内容都是不同的,并且似乎是随机的。
答案 0 :(得分:1)
您看到的字符串java.lang.ProcessImpl@12a337b
是
toString()
返回的Process
结果由
Runtime.getRuntime().exec("....")
。
您可能不希望看到此过程的退出代码(在您的情况下为5
)。
要获取它,您必须等待该过程完成,然后获取其退出代码:
Process process = Runtime.getRuntime().exec("cmd /c start file1.py main()");
process.waitFor();
int exitCode = process.exitValue();
System.out.println(exitCode);
有关更多信息,请参见django.db.connection,Object.toString()
和Process.waitFor()
的javadoc。
答案 1 :(得分:0)
当您这样做:
System.out.println("Failed" + e);
您正在使用默认的IOException
方法打印出toString()
对象。您要使用getMessage()
方法:
System.out.println("Failed" + e.getMessage());
答案 2 :(得分:0)
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\nsys.path.append('pathToModules if they are not there by default')\nimport yourModule");
// execute a function that takes a string and returns a string
PyObject someFunc = interpreter.get("funcName");
PyObject result = someFunc.__call__(new PyString("Test!"));
String realResult = (String) result.__tojava__(String.class);
尝试