Bundling python files inside jar for access via jython

寵の児 提交于 2019-12-08 01:50:40

问题


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



来源:https://stackoverflow.com/questions/6260311/bundling-python-files-inside-jar-for-access-via-jython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!