简体   繁体   中英

Adding arguments in Jython PythonInterpreter to the “execfile” function

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM