Can I make a jar execute a python script?

余生长醉 提交于 2019-12-25 00:00:12

问题


Is there some way to call a script within a jar without extracting it?


回答1:


Python will interpret a file named "__main__.py" stored inside a zip file, if called with one as a parameter. Since jar files are zips, all you have to do is name your Python script as "__main__.py", or create a "__main__.py" script that imports your main script, and from Java, invoke the Python interpreter as an external process, passing the .jar file path as its sole argument. (Importing other Python modules from within the Python script will work as if the .jar file where a directory structure)

You can then communicate with the Python process via pipe (stdin/stdout) or using some client/server approach (xmlrpc, Unix named pipes, etc...)

Another option would be to use Jython - the JVM based Python interpreter, so that you can call Python code directly from your java code - there are several options to integrate Jython code into java programs, some of witch are described here: http://jythonpodcast.hostjava.net/jythonbook/en/1.0/JythonAndJavaIntegration.html#using-jython-within-java-applications




回答2:


As JAR files are zip archives, you can unzip a single file to standard output and pipe to Python.

unzip -p your.jar file_in_jar.py | python



回答3:


If you just want pure python, then you can use zipfile. Then you could use something like subprocess or this if the file is already compiled

If you want to use it from java code, you could use something similar to loading a class/resource in a jar file. A variant is present here and another one here. I haven't tried this.



来源:https://stackoverflow.com/questions/8392875/can-i-make-a-jar-execute-a-python-script

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