将变量从 java 传递到 python 脚本
Passing variables to a python script from java
好的,所以 here 是已经提出的问题,但答案似乎没有多大帮助。我可以使用 jython 运行 python 脚本和该问题中发布的答案,但我无法传递变量...当我 运行 程序错误说没有这样的变量为 arg1 arg2 和 arg3 ...我做错了什么?
String[] arguments = {"myscript.py", "arg1", "arg2", "arg3"};
PythonInterpreter.initialize(System.getProperties(), System.getProperties(),arguments);
org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter();
StringWriter out = new StringWriter();
python.setOut(out);
python.execfile("myscript.py");
String outputStr = out.toString();
System.out.println(outputStr);
这里是 python 脚本
def myFunction(arg1,arg2,arg3):
print "calling python function with paramters:"
print arg1
print arg2
print arg3
myFunction(arg1,arg2,arg3)
现在错误提示 arg1 arg2 和 arg3 未声明
您应该通过 sys.argv
变量访问命令行参数,如下所述:https://www.tutorialspoint.com/python/python_command_line_arguments.htm
所以正确的代码:
myFunction(sys.argv[0], sys.argv[1], sys.argv[2])
好的,所以 here 是已经提出的问题,但答案似乎没有多大帮助。我可以使用 jython 运行 python 脚本和该问题中发布的答案,但我无法传递变量...当我 运行 程序错误说没有这样的变量为 arg1 arg2 和 arg3 ...我做错了什么?
String[] arguments = {"myscript.py", "arg1", "arg2", "arg3"};
PythonInterpreter.initialize(System.getProperties(), System.getProperties(),arguments);
org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter();
StringWriter out = new StringWriter();
python.setOut(out);
python.execfile("myscript.py");
String outputStr = out.toString();
System.out.println(outputStr);
这里是 python 脚本
def myFunction(arg1,arg2,arg3):
print "calling python function with paramters:"
print arg1
print arg2
print arg3
myFunction(arg1,arg2,arg3)
现在错误提示 arg1 arg2 和 arg3 未声明
您应该通过 sys.argv
变量访问命令行参数,如下所述:https://www.tutorialspoint.com/python/python_command_line_arguments.htm
所以正确的代码:
myFunction(sys.argv[0], sys.argv[1], sys.argv[2])