Jython 2.5.1:从 Java 调用到 __main__ - 如何传入命令行参数? [英] Jython 2.5.1: Calling From Java into __main__ - how to pass in command line args?

查看:27
本文介绍了Jython 2.5.1:从 Java 调用到 __main__ - 如何传入命令行参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

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

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

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

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

如果您需要 argv[0] 作为实际脚本名称,您需要像这样创建状态:

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

那么输出是:

hello
['myscript.py', 'arg1', 'arg2']

这篇关于Jython 2.5.1:从 Java 调用到 __main__ - 如何传入命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆