簡體   English   中英

在Java代碼中將PythonInterpreter與Jython結合使用

[英]Use PythonInterpreter with Jython in Java Code

在終端中輸入jython時,我得到:

Jython 2.2.1 on java1.7.0_51

我想在我的Java代碼中使用NLTK POS。 我跟隨@Vicent回答如何使用jython jar將python 模塊添加到java中以使用python解釋器,

package myjythonproject;

import org.python.util.PythonInterpreter;

public class MyJythonProject {

public static void main(String[] args) {
    try
    {
        PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]);
        PythonInterpreter interp = new PythonInterpreter();
        interp.execfile("/home/vicent/foo.py");
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
 }
}

只需對代碼進行一次更改:

interp.execfile("/Users/ha/Desktop/Code.py"); 

沒有錯誤,但是Code.py的內容未顯示(僅打印Hello world)。

if __name__ == "__main__":
    print "Hello World";

我已經編輯了從終端到jython lib文件夾的系統路徑。

我該如何運作?

更新:

在if語句之前添加print __name__之后(如@MikeRixWolfe所建議),得到以下輸出:

run:
main
BUILD SUCCESSFUL (total time: 1 second)

所以我將其編輯為if __name__ == "main":並且可以使用!

__name__可能不是 __main__因為它是從Java程序而非直接調用的。 嘗試將print __name__放在if語句上方以進行驗證

暫無
暫無

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

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