Jython 2.5.1: Calling From Java into __main__ - how to pass in command line args?

心不动则不痛 提交于 2019-12-21 17:52:06

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/6467407/jython-2-5-1-calling-from-java-into-main-how-to-pass-in-command-line-args

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!