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!

4

1 Answer

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest