Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java with Jython, elegant way to solve path trouble?

i have piece of Java code, using Jython to call some Python library, this library rely on external Jython classic libraryies like re for regular expression and others, so i have this kind of code :

    PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState()); 
    PySystemState sys = Py.getSystemState(); 

    // below: so that my own library find necessary 'batteries included' Python libs
    sys.path.append(new PyString("C:/jython2.5.2/Lib")); // (path1)
    // below: i put my own Python library inside the Java package for clarity
    // and be able to package everything in jar, well, maybe is it no a good idea?
    // also i am wondering, because myfile.py remain inside /src subdirectories 
    // while after compiling Eclipse will put most in /bin subidrectories but not the *.py files
    // thus doing some:
    //    MyJythonFactory..class.getProtectionDomain().getCodeSource().getLocation().toString() 
    // will not help to rebuild the ..myJavaProject/src/my/domain/mypackage
    sys.path.append(new PyString("D:/eclipseWorkspace/myJavaProject/src/my/domain/mypackage")); (path2)

    interpreter.exec("from mylib import myfunc"); //(A)
    PyObject myPyFunction = interpreter.get("myfunc");

BTW, i do not like the fact that i need to change and hard code both path (path1) and (path2)

do you see an elegant way to avoid this and to add some 'whereami' autodetect path features (at least for (path2))?

and looks like i need both (path1) and (path2) => so that (A) works!

i can also reformulated my question as what elegant way would you find to do not have any ImportError: No module named myModule or how to avoid hardcoding something like:

 PySystemState sys = Py.getSystemState(); 
 sys.path.append("where/my/python/libs/live/while/they/are/at/the/same/place/as/my/current/java/class")

best regards

like image 451
user1340802 Avatar asked Jun 23 '26 23:06

user1340802


1 Answers

make sure you have the jython-standalone.jar not jython.jar in your project classpath because jython-standalone.jar has Python Lib inside the jar so that you don't need append it to sys.path.

if you are using maven, you can add this to pom.xml :

<dependency>
    <groupId>org.python</groupId>
    <artifactId>jython-standalone</artifactId>
    <version>2.7.0</version>
</dependency>

or you can download jar here.

for you own python module put it in the java project classpath, Jython use java classplath as __pyclasspath__, so you avoid hardcoding.

like image 200
kk17 Avatar answered Jun 25 '26 12:06

kk17



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!