简体   繁体   中英

Passing arguments to Python script in Java

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 ?

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.

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

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

I am using Jython 2.5.3. Hope this will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM