【问题标题】:Passing variables to a python script from java从java将变量传递给python脚本
【发布时间】:2017-02-18 16:19:10
【问题描述】:

好的,所以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 未声明

【问题讨论】:

    标签: java python jython


    【解决方案1】:

    您应该通过sys.argv 变量访问命令行参数,如下所述:https://www.tutorialspoint.com/python/python_command_line_arguments.htm

    所以正确的代码:

    myFunction(sys.argv[0], sys.argv[1], sys.argv[2])
    

    【讨论】:

      猜你喜欢
      • 2021-08-14
      • 1970-01-01
      • 2015-06-25
      • 2019-07-28
      • 2012-10-15
      • 1970-01-01
      • 2011-12-03
      • 2013-10-24
      • 2016-11-13
      相关资源
      最近更新 更多