2

In the following code I simply execute test.py from java code using jython

public static void main(String[] args) {
  org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter();
  python.execfile("test.py");
  ...

My problem is test.py needs to be in same directory from where jar file is run.
I need this test.py bundled inside the jar and still be able to execute it using jython.

Approach suggested in How do you invoke a python script inside a jar file using python? to read the script in string using getResourceAsStream method from ClassLoader class wont work for me as my test.py imports more python scripts all bundled inside the jar.

Being new to java and jython i'm really confused.
Any help will be highly appreciated..!

2 Answers 2

6

You can simply put test.py at the root of the jar, with the other scripts organized as they would be on the fs in normal python. Then you can do something like that:

public static void main(String[] args) {
  org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter();
  python.exec("import test");
  python.exec("test.callsomthing()");
}

the import in test.py should work as normal, including importing other modules from test.py.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks!! do u know how to put a file at root of jar using netbeans? (sorry, i havent used jar packaging before)
got how to add at root of jar from stackoverflow.com/questions/3955299/… . Thanks a lot!! stackoverflow rocks :)
@Daniel I am facing ImportError: no module named test class test: def __init__(self): pass def hello(self): print("Hello Python function call..!") test.py in the same folder.
0

Extract the python file from the jar by using the "getResourceAsStream" of the class.

See for example: http://fiji.sc/wiki/index.php/Jython_Scripting#Distributing_jython_scripts_in_a_.jar_file

2 Comments

I understand that what you are suggesting is reading whole python file in a string and then execuing it as suggested in stackoverflow.com/questions/2551269/…. But problem with this is I have multiple python modules, so more python modules inside jar which are imported from this test.py which wont work in this way.
@Nullpoet, the PythonInterpreter class has methods to execute files, which, for a script that only declares functions and classes, is the equivalent of loading it. So load them all in the same PythonInterpreter instance and then execute the script that depends on the others. An alternative is to copy all .py files to a temporary directory, and then add that directory to the classpath with: from sys import path; path.append('/path/to/temp/dir')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.