Python Jython 解释器

Python Interpreter in Jython

我想做的就是将一个参数传递给 python 解释器,以便它可以作为模块的参数传递。

例如我在 py 文件中定义了以下内容:

    def print_twice(test):
       print test
       print test

我想给它传递参数 "Adam",所以我试过了:

    // Create an instance of the PythonInterpreter
    PythonInterpreter interp = new PythonInterpreter();

    // The exec() method executes strings of code
    interp.exec("import sys");
    interp.exec("print sys");

    PyCode pyTest = interp.compile("Adam", "C:/Users/Adam/workspace/JythonTest/printTwice.py");
    System.out.println(pyTest.toString());

我也试过了:

        interp.eval("print_twice('Adam')");

我一直在使用以下 Jython API 但我不太了解它: http://www.jython.org/javadoc/org/python/util/PythonInterpreter.html#compile%28java.lang.String,%20java.lang.String%29

非常感谢您的建议。

谢谢

这应该有效:

interp.exec("import YOUR_PYTHON_FILE.py");
interp.exec("YOUR_PYTHON_FILE.print_twice('Adam')");

它在 python 控制台中的等价物是这样的:

>>> import YOUR_PYTHON_FILE.py
>>> YOUR_PYTHON_FILE.print_twice('Adam')
Adam
Adam

您不需要显式编译脚本,只需导入它,解释器将负责编译。像这样的东西(假设 printTwice.py 在你程序的工作目录中:

interp.exec("from printTwice import print_twice");
interp.exec("print_twice('Adam')");

假设 print_twice 实际上包含 print 语句,则不需要在第二行使用 interp.eval;如果它只是 returns 一个字符串那么你可能想要
System.out.println(interp.eval("print_twice('Adam')"));.