smuggledPancakes
smuggledPancakes

Reputation: 10323

Can I make a jar execute a python script?

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

Upvotes: 0

Views: 3704

Answers (3)

jsbueno
jsbueno

Reputation: 110156

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

Upvotes: 2

Laur Ivan
Laur Ivan

Reputation: 4177

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.

Upvotes: 0

Jan
Jan

Reputation: 11726

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

Upvotes: 3

Related Questions