Bundling python files inside jar for access via jy

2019-05-24 11:26发布

问题:

In the following code I simply execute test.py from java code using jython

public static void main(String[] args) {
  org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter();
  python.execfile("test.py");
  ...

My problem is test.py needs to be in same directory from where jar file is run.
I need this test.py bundled inside the jar and still be able to execute it using jython.

Approach suggested in How do you invoke a python script inside a jar file using python? to read the script in string using getResourceAsStream method from ClassLoader class wont work for me as my test.py imports more python scripts all bundled inside the jar.

Being new to java and jython i'm really confused.
Any help will be highly appreciated..!

回答1:

You can simply put test.py at the root of the jar, with the other scripts organized as they would be on the fs in normal python. Then you can do something like that:

public static void main(String[] args) {
  org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter();
  python.exec("import test");
  python.exec("test.callsomthing()");
}

the import in test.py should work as normal, including importing other modules from test.py.



回答2:

Extract the python file from the jar by using the "getResourceAsStream" of the class.

See for example: http://fiji.sc/wiki/index.php/Jython_Scripting#Distributing_jython_scripts_in_a_.jar_file