Jython 2.5.1: a call from Java to __main__ - how to pass args on the command line?

I am using Jython from Java; so I have a Java setup as shown 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 example) run the script below:

 # myscript.py: import sys if __name__=="__main__": print "hello" print sys.argv 

How to pass command line arguments using this method? (I want to write Jython scripts so that I can also run them on the command line using "python script arg1 arg2").

+4
source share
2 answers

I am using Jython 2.5.2 and runScript does not exist, so I had to replace it with execfile . Besides this 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 previous code displays the result:

 hello ['', 'arg1', 'arg2'] 

If you need argv[0] be the actual name of the script, you need to create the state as follows:

 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 output:

 hello ['myscript.py', 'arg1', 'arg2'] 
+9
source

For those people whose above solution does not work, try the following. 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 command repeats the command below. that is, each argument and its value are a separate element in the 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); 
0
source

All Articles