Python Interpreter in Jython

徘徊边缘 提交于 2020-01-06 19:52:15

问题


All I'm trying to do is pass an argument to the python interpreter so it can be passed as an argument for a module.

E.g. I have the following defined in a py file:

    def print_twice(test):
       print test
       print test

I want to pass it the argument "Adam", so I've tried:

    // 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());

I've also tried:

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

I've been using the following Jython API but I don't understand it well: http://www.jython.org/javadoc/org/python/util/PythonInterpreter.html#compile%28java.lang.String,%20java.lang.String%29

I would be very grateful for your advices.

Thank you


回答1:


This should work:

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

Its equivalent in a python console is this:

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



回答2:


You shouldn't need to explicitly compile the script, just import it and the interpreter will take care of compilation. Something like this (assuming printTwice.py is in the working directory of your program:

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

You don't need to use interp.eval on the second line assuming that print_twice does actually contain print statements; if it just returns a string then you probably want
System.out.println(interp.eval("print_twice('Adam')"));.



来源:https://stackoverflow.com/questions/31752559/python-interpreter-in-jython

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!