Jython 2.5.1:从Java调用__main__ - 如何传入命令行参数?

mon*_*nny 4 command-line jython argv argc

我在Java中使用Jython; 所以我有一个类似于下面的Java设置:

String scriptname="com/blah/myscript.py"
PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState());
InputStream is = this.getClass().getClassLoader().getResourceAsStream(scriptname);
interpreter.execfile(is);
Run Code Online (Sandbox Code Playgroud)

这将(例如)运行以下脚本:

# myscript.py:
import sys

if __name__=="__main__":
    print "hello"
    print sys.argv
Run Code Online (Sandbox Code Playgroud)

我如何使用此方法传递'命令行'参数?(我希望能够编写我的Jython脚本,以便我也可以使用'python script arg1 arg2'在命令行上运行它们).

101*_*100 9

我正在使用Jython 2.5.2并且runScript不存在,所以我不得不替换它execfile.除了这个差异,我还需要argv在创建对象之前设置状态PythonInterpreter对象:

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);
Run Code Online (Sandbox Code Playgroud)

argv状态对象中的列表最初的长度为1,其中包含空字符串,因此前面的代码会产生输出:

hello
['', 'arg1', 'arg2']
Run Code Online (Sandbox Code Playgroud)

如果您需要argv[0]是实际的脚本名称,则需要创建如下状态:

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"));
Run Code Online (Sandbox Code Playgroud)

然后输出是:

hello
['myscript.py', 'arg1', 'arg2']
Run Code Online (Sandbox Code Playgroud)