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– Beau Grantham2011-12-05 22:40:31 +00:00Commented Dec 5, 2011 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– Brigand2011-12-05 23:42:27 +00:00Commented Dec 5, 2011 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– jsbueno2011-12-06 02:02:37 +00:00Commented Dec 6, 2011 at 2:02
3 Answers
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
Comments
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.