Jython 2.5.1: Calling From Java into __main__ - how to pass in command line args?
I'm using Jython from within Java; so I have a Java setup similar to below:
String scriptname="com/blah/myscript.py"
PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState());
InputStream is = this.getClass().getClassLoader().getResourceAsStream(scriptname);
interpreter.execfile(is);
And this will (for instance) run t开发者_开发百科he script below:
# myscript.py:
import sys
if __name__=="__main__":
print "hello"
print sys.argv
How I pass in 'commandline' arguments using this method ? (I want to be able to write my Jython scripts so that I can also run them on the commandline with 'python script arg1 arg2').
I'm using Jython 2.5.2 and runScript
didn't exist, so I had to replace it with execfile
. Aside from that difference, I also needed to set argv
in the state object before creating the PythonInterpreter
object:
String scriptname = "myscript.py";
PySystemState state = new PySystemState();
state.argv.append (new PyString ("arg1"));
state.argv.append (new PyString ("arg2"));
PythonInterpreter interpreter = new PythonInterpreter(null, state);
InputStream is = Tester.class.getClassLoader().getResourceAsStream(scriptname);
interpreter.execfile (is);
The argv
list in the state object initially has a length of 1, with an empty string in it, so the preceding code results in the output:
hello
['', 'arg1', 'arg2']
If you need argv[0]
to be the actual script name, you'd need to create the state like this:
PySystemState state = new PySystemState();
state.argv.clear ();
state.argv.append (new PyString (scriptname));
state.argv.append (new PyString ("arg1"));
state.argv.append (new PyString ("arg2"));
Then the output is:
hello
['myscript.py', 'arg1', 'arg2']
For those people whom the above solution does not work, try the below. This works for me on jython version 2.7.0
String[] params = {"get_AD_accounts.py","-server", "http://xxxxx:8080","-verbose", "-logLevel", "CRITICAL"};
The above replicates the command below. i.e. each argument and its value is separate element in params array.
jython get_AD_accounts.py -logLevel CRITICAL -server http://xxxxxx:8080 -verbose
PythonInterpreter.initialize(System.getProperties(), System.getProperties(), params);
PySystemState state = new PySystemState() ;
InputStream is = new FileInputStream("C:\\projectfolder\\get_AD_accounts.py");
PythonInterpreter interp = new PythonInterpreter(null, state);
PythonInterpreter interp = new PythonInterpreter(null, state);
interp.execfile(is);
精彩评论