问题
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!
回答1:
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");
来源:https://stackoverflow.com/questions/18357521/using-processbuilder-to-execute-a-python-script-with-command-line-options