Passing arguments to Python script in Java

2019-07-30 07:54发布

问题:

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.