简体   繁体   中英

Use PythonInterpreter with Jython in Java Code

When I type jython in terminal I get:

Jython 2.2.1 on java1.7.0_51

I want to use the NLTK POS in my java code. I followed @Vicent answer in how to add module of python into java using jython jar to use python interpreter,

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

with only one change on the code:

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

there is no error but the content of Code.py is not displayed(which is only printing Hello world).

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

I've edit the system path from terminal to the jython lib folder.

How can I make it work?

UPDATE:

After I added print __name__ before the if statement - As suggested by @MikeRixWolfe - and I got this output:

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

so I edit it to if __name__ == "main": and it works!

Likely the __name__ is not __main__ due to it being called from the java program, rather than directly. Try placing print __name__ above the if statement to verify

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM