我正在使用 Python 3.4 。
我有一个Python脚本myscript.py
:
import sys
def returnvalue(str) :
if str == "hi" :
return "yes"
else :
return "no"
print("calling python function with parameters:")
print(sys.argv[1])
str = sys.argv[1]
res = returnvalue(str)
target = open("file.txt", 'w')
target.write(res)
target.close()
我需要从java类PythonJava.java
public class PythonJava
{
String arg1;
public void setArg1(String arg1) {
this.arg1 = arg1;
}
public void runPython()
{ //need to call myscript.py and also pass arg1 as its arguments.
//and also myscript.py path is in C:\Demo\myscript.py
}
我通过创建runPython()
的对象
PythonJava
obj.setArg1("hi");
...
obj.runPython();
我尝试了很多方法,但没有一个方法正常工作。我使用了Jython和ProcessBuilder,但脚本没有写入file.txt。你能建议一种正确实施的方法吗?
答案 0 :(得分:2)
Call Python code from Java by passing parameters and results
How to call a python method from a java class?
简而言之,一个解决方案可能是:
public void runPython()
{ //need to call myscript.py and also pass arg1 as its arguments.
//and also myscript.py path is in C:\Demo\myscript.py
String[] cmd = {
"python",
"C:/Demo/myscript.py",
this.arg1,
};
Runtime.getRuntime().exec(cmd);
}
编辑:只需确保将变量名称从str更改为其他名称,如cdarke
所述您的python代码(将str更改为其他内容,例如arg并指定文件路径):
def returnvalue(arg) :
if arg == "hi" :
return "yes"
return "no"
print("calling python function with parameters:")
print(sys.argv[1])
arg = sys.argv[1]
res = returnvalue(arg)
print(res)
with open("C:/path/to/where/you/want/file.txt", 'w') as target: # specify path or else it will be created where you run your java code
target.write(res)
答案 1 :(得分:1)
可以使用以下简单方法通过Java从Argument调用python并在java控制台中打印python输出:
ApiRestTest
答案 2 :(得分:0)
下面是带有三个示例参数的python方法,以后可以通过java调用它们。
#Sample python method with arguments
import sys
def getDataFromJava(arg1,arg2,arg3):
arg1_val="Hi"+arg1
arg2_val=arg2
arg3_val=arg3
print(arg1_val)
print(arg2_val)
print(arg3_val)
return arg1_val,arg2_val,arg3_val
arg1 = sys.argv[1]
arg2 = sys.argv[2]
arg3 = sys.argv[3]
getDataFromJava(arg1,arg2,arg3)
下面是使用三个示例参数调用上述方法的Java代码,并通过InputStreamReader读取java中python脚本的控制台输出。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test1 {
public static String s;
public static void main(String[] args) throws IOException {
String pathPython = "Path_to_the_file\\test.py";
String [] cmd = new String[5];
cmd[0] = "python";
cmd[1] = pathPython;
cmd[2] = "arg1";
cmd[3] = "arg2";
cmd[4] = "arg3";
Runtime r = Runtime.getRuntime();
Process p = r.exec(cmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((s=in.readLine()) != null){
System.out.println(s);
}
}
}