I have a python script that I would like to execute in Java with Jython. The Python script accepts 2 arguments. How can I add arguments to the script?
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("C:/path/to/file/__main__.py");
Thank you!
execfile
executes the script in the local namespace. You could simply assign the value to sys.argv
in a prior call to exec
:
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec(
"import sys\n"
+"sys.argv = ['Foo', 'Bar']");
interpreter.execfile("J:/test.py");
Where the script is:
import sys
print(sys.argv)
prints:
['Foo', 'Bar']
I looked into the question of your comment, and it looks like you would need to set python.path
in a Properties
object that you then pass to PythonInterpreter.initialize
. You could also use this to pass the arguments:
Properties p = new Properties();
p.setProperty("python.path", "J:/WS/jython"); // Sets the module path
PythonInterpreter.initialize(System.getProperties(), p, new String[]{ "Foo", "Bar" });
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("J:/WS/jython/main.py");