Search code examples
command-linejythonargvargc

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 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').


Solution

  • 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']