Is there some way to call a script within a jar without extracting it?
-
1Your title and question seem to conflict.. or at least I don't get it. Maybe you could clarify and expand on what you're trying to do. – Beau Grantham Dec 05 '11 at 22:40
-
My understanding of it is, "How do I use a Java program to execute a Python script contained in the Java program's own Jar-archive?" Is that correct? – Brigand Dec 05 '11 at 23:42
-
1@BeauGrantham I don't have a problem understanding the question. The reading in the comment above seems to be the only possible one. – jsbueno Dec 06 '11 at 02:02
3 Answers
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

- 11,636
- 38
- 47
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

- 99,910
- 10
- 151
- 209
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.