我在 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);
这将(例如)运行下面的脚本:
# myscript.py:
import sys
if __name__=="__main__":
print "hello"
print sys.argv
如何使用此方法传递“命令行”参数?
(我希望能够编写 Jython 脚本,以便我也可以使用“python script arg1 arg2”在命令行上运行它们)。
我正在使用 Jython 2.5.2 和runScript
不存在,所以我必须将其替换为execfile
。除了这个区别之外,我还需要设置argv
在创建之前的状态对象中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
状态对象中的列表最初的长度为 1,其中有一个空字符串,因此前面的代码会产生以下输出:
hello
['', 'arg1', 'arg2']
如果你需要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"));
那么输出是:
hello
['myscript.py', 'arg1', 'arg2']
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)