How do you call a python script inside a jar file using python?

I am working on an application that interleaves a bunch of jython and java code. Due to the nature of the program (using wsadmin) we are really limited to Python 2.1

We currently have a jar containing both java and .py sources. The code is currently being called using java, but I would like to remove this in favor of porting as many functions as possible to jython.

The problem is that I want to either import or execute python modules inside an existing jar file from the calling jython script. I tried a couple of different ways without success.

My directory structure looks like this:

application.jar |-- com |--example |-- action |-- MyAction.class |-- pre_myAction.py 

The first approach I tried was to import from a can. I added the jar to my sys.path and tried to import the module using both import com.example.action.myAction and import myAction . However, no success, even when I put init .py files in a directory at each level.

The second approach I tried was to load a resource using the java class. So I wrote the code below:

 import sys import os import com.example.action.MyAction as MyAction scriptName = str(MyAction.getResource('/com/example/action/myAction.py')) scriptStr = MyAction.getResourceAsStream('/com/example/action/myAction.py') try: print execfile(scriptStr) except: print "failed 1" try: print execfile(scriptName) except: print "failed 2" 

Both of them failed. Now I am a little lost, how should I go further. Any ideas?

amuses

Trevor

+6
java python import jar jython
source share
1 answer

the following works for me:

 import sys import os import java.lang.ClassLoader import java.io.InputStreamReader import java.io.BufferedReader loader = java.lang.ClassLoader.getSystemClassLoader() stream = loader.getResourceAsStream("com/example/action/myAction.py") reader = java.io.BufferedReader(java.io.InputStreamReader(stream)) script = "" line = reader.readLine() while (line != None) : script += line + "\n" line = reader.readLine() exec(script) 
  • Loading Script from ClassPath as a string in 'script'
  • execute script with exec
+5
source share

All Articles