簡體   English   中英

Jython中的Python解釋器

[英]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語句, print_twice無需在第二行中使用interp.eval 如果它只是返回一個字符串,那么您可能想要
System.out.println(interp.eval("print_twice('Adam')"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM