将参数传递给Java中的Python脚本 [英] Passing arguments to Python script in Java

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

问题描述

我正在这样的java类中运行python脚本:

I'm running a python script in a java class like this:

PythonInterpreter interp = new PythonInterpreter();
PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]);
interp.execfile("C:\\Users\\user1\\workspace\\Projectx\\script.py");

问题在于script.py通常采用这样的命令行参数:

The problem is that script.py usually takes commandline arguments like this:

python script.py -i C:/目录/路径-o C:/目录/路径

python script.py -i C:/diretory/path -o C:/directory/path

是否可以通过Java中的PythonIntepereter传递这些参数?

Is it possible to pass those arguments via the PythonIntepereter in Java ?

更新:

感谢Juned Ahsan,我的代码现在看起来像这样:

Thx to Juned Ahsan my code now looks like this:

String[] args = {"-i " + lawlinkerIfolder.toString() + " -o " + lawlinkerOfolder.toString()};
PythonInterpreter interp = new PythonInterpreter();
PythonInterpreter.initialize(System.getProperties(), System.getProperties(), args);
interp.execfile("C:\\Users\\user1\\workspace\\Projectx\\script.py");

但是脚本仍然没有得到任何参数.

But the script is still not getting any arguments.

我正确使用了吗?

推荐答案

下面的调用中的最后一个参数用于命令行参数:

Last argument in your below call is for command line arguments:

PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]);

来自 PythronInterpreter javadocs :

初始化

public static void initialize(Properties preProperties, 属性postProperties, String [] argv)

public static void initialize(Properties preProperties, Properties postProperties, String[] argv)

初始化Jython运行时.这应该只被调用一次, 在任何其他Python对象(包括PythonInterpreter)之前 创建.参数:preProperties-一组属性.通常 使用System.getProperties(). preProperties覆盖来自的属性 注册表文件. postProperties-另一组属性.价值观 像python.home,python.path以及注册表中的所有其他值 可以将文件添加到此属性集. postProperties覆盖 系统属性和注册表属性. argv-命令行参数,分配给sys.argv.

Initializes the Jython runtime. This should only be called once, before any other Python objects (including PythonInterpreter) are created. Parameters: preProperties - A set of properties. Typically System.getProperties() is used. preProperties override properties from the registry file. postProperties - Another set of properties. Values like python.home, python.path and all other values from the registry files can be added to this property set. postProperties override system properties and registry properties. argv - Command line arguments, assigned to sys.argv.

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

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