【问题标题】:Adding arguments in Jython PythonInterpreter to the "execfile" function将 Jython PythonInterpreter 中的参数添加到“execfile”函数
【发布时间】:2017-03-03 21:51:26
【问题描述】:

我有一个 python 脚本,我想用 Jython 在 Java 中执行它。 Python 脚本接受 2 个参数。如何向脚本添加参数?

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("C:/path/to/file/__main__.py");

谢谢!

【问题讨论】:

    标签: java python jython


    【解决方案1】:

    execfile 在本地命名空间中执行脚本。您可以在之前调用exec 时简单地将值分配给sys.argv

    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.exec(
        "import sys\n"
        +"sys.argv = ['Foo', 'Bar']");
    interpreter.execfile("J:/test.py");
    

    脚本在哪里:

    import sys
    
    print(sys.argv)
    

    打印:

    ['Foo', 'Bar']
    

    我查看了您的评论问题,看起来您需要在 Properties 对象中设置 python.path,然后将其传递给 PythonInterpreter.initialize。您也可以使用它来传递参数:

    Properties p = new Properties();
    p.setProperty("python.path", "J:/WS/jython"); // Sets the module path
    
    PythonInterpreter.initialize(System.getProperties(), p, new String[]{ "Foo", "Bar" });
    
    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.execfile("J:/WS/jython/main.py");
    

    【讨论】:

    • 感谢@Jorn Vernee 如果我的 Python 脚本包含多个文件,那么我需要以某种方式导入它们吗?
    • 感谢@Jorn 的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    相关资源
    最近更新 更多