gpt4 book ai didi

java - 将变量从java传递给python脚本

转载 作者:行者123 更新时间:2023-11-30 10:33:16 24 4
gpt4 key购买 nike

好吧 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])

关于java - 将变量从java传递给python脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42312768/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com