Using ProcessBuilder to execute a python script with command line options

不打扰是莪最后的温柔 提交于 2019-12-02 03:46:26

问题


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

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