Jython 2.5.1:从 Java 调用 __main__ - 如何传入命令行参数?
我在 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”在命令行上运行它们)。
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').
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我使用的是 Jython 2.5.2,但
runScript
不存在,因此我必须将其替换为execfile
。除了这个区别之外,我还需要在创建 PythonInterpreter 对象之前在状态对象中设置 argv :最初状态对象中的 argv 列表长度为 1,其中有一个空字符串,因此前面的代码会产生以下输出:
如果您需要
argv[0]
作为实际的脚本名称,则需要创建像这样的状态:那么输出是:
I'm using Jython 2.5.2 and
runScript
didn't exist, so I had to replace it withexecfile
. Aside from that difference, I also needed to setargv
in the state object before creating thePythonInterpreter
object: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:If you need
argv[0]
to be the actual script name, you'd need to create the state like this:Then the output is:
对于上述解决方案不起作用的人,请尝试以下解决方案。这适用于 jython 版本 2.7.0
上面复制了下面的命令。即每个参数及其值是 params 数组中的单独元素。
jython get_AD_accounts.py -logLevel CRITICAL -server http://xxxxxx:8080 -verbose
For those people whom the above solution does not work, try the below. This works for me on jython version 2.7.0
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