如何使用jython将参数传递给java中的python脚本 [英] how to pass arguments to python script in java using jython

查看:376
本文介绍了如何使用jython将参数传递给java中的python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jython在Java中执行我的python脚本. 重要的是我需要使用jython将命令行参数传递给脚本,例如myscript.py arg1 arg2 arg3. 这里有一个类似的问题:将参数传递给Java中的Python脚本

I am trying to execute my python script in java using jython. The important thing is that I need to pass command line arguments to my script using jython, e.g. myscript.py arg1 arg2 arg3. There is a similar question here: Passing arguments to Python script in Java

未完全回答(解决方案均无效).

Which was not answered completely (none of the solutions work).

我的代码现在看起来像这样:

My code now looks like this:

String[] arguments = {"arg1", "arg2", "arg3"}; 
PythonInterpreter.initialize(props, System.getProperties(), arguments);
org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter();
StringWriter out = new StringWriter();
python.setOut(out);
python.execfile("myscript.py");
String outputStr = out.toString();
System.out.println(outputStr);

但是,这似乎没有将任何参数传递给python脚本. 有什么建议如何正确地做吗? 它必须很简单,但是我在网上找不到任何文档.

However, this does not seem to pass any arguments to the python script. Any suggestions how to do it properly? It must be simple, but I can't find any documentation on the web.

我正在使用python 2.7和jython 2.7.0.

I am using python 2.7 and jython 2.7.0.

推荐答案

同时,我找到了一个解决方案.在这里:

In the meantime, I have found a solution. Here it is:

String[] arguments = {"myscript.py", "arg1", "arg2", "arg3"};
PythonInterpreter.initialize(System.getProperties(), System.getProperties(), arguments);
org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter();
StringWriter out = new StringWriter();
python.setOut(out);
python.execfile("myscript.py");
String outputStr = out.toString();
System.out.println(outputStr);

我需要做的仅仅是将我的脚本作为arg [0]添加到传递的参数中(请参见代码的第一行)!

What I needed to do was simply to add my script to the passed parameters as arg[0] (see the first line of the code)!

这篇关于如何使用jython将参数传递给java中的python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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