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 the 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
runScriptdidn’t exist, so I had to replace it withexecfile. Aside from that difference, I also needed to setargvin the state object before creating thePythonInterpreterobject:The
argvlist in the state object initially has a length of 1, with an empty string in it, so the preceding code results in the output:If you need
argv[0]to be the actual script name, you’d need to create the state like this:Then the output is: