简体   繁体   中英

Using ProcessBuilder to execute a python script with command line options

in order to execute a python script(which has several command line parameters) from Java, I am trying to use is the following java code

String[] command = {"script.py", "run",
                    "-arg1", "val1", 
                    "-arg2", "val2" ,          
                    "-arg3" , "val_31 val_32",
       };

ProcessBuilder probuilder = new ProcessBuilder( command );
Process process = probuilder.start();

For instance I intend to execute the following command:

./script.py run -arg1 val1 -arg2 val2 -arg3 val_31 val_32

note that the parameter arg3 takes a list of parameter values.

The problem I am facing is that I did not find a way to pass a list of values to the parameter arg3.

I would really appreciate if someone could give me some hints in order to tackling my problem.

I already did a search but I could not find a suitable answer for my needs, if someone find the right link please let me know.

Best!

Just give them as separate strings in the array, instead of combining the last two into "val_31 val_32" :

String[] command = {"script.py", "run",
                    "-arg1", "val1", 
                    "-arg2", "val2" ,          
                    "-arg3" , "val_31", "val_32",
       };

Otherwise it will escape the space in between val_31 and val_32 because you are telling it that they're a single parameter. Incidentally, you can also use the varargs constructor and skip having to create an array, if you want:

ProcessBuilder probuilder = new ProcessBuilder( "script.py", "run",
                    "-arg1", "val1", 
                    "-arg2", "val2" ,          
                    "-arg3" , "val_31", "val_32");

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