Passing arguments to Python script in Java

给你一囗甜甜゛ 提交于 2019-12-11 08:48:02

问题


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

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

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

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

Update:

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.

Am I using this correctly ?


回答1:


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

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

From PythronInterpreter javadocs:

initialize

public static void initialize(Properties preProperties, Properties postProperties, String[] 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.




回答2:


I had the same issue and found it could be resolved by using "interned" string, i.e.,

for (int i = 0; i args.length; ++i) {
    args[i] = args[i].intern();
}

I am using Jython 2.5.3. Hope this will help.



来源:https://stackoverflow.com/questions/17466628/passing-arguments-to-python-script-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!