使用ProcessBuilder使用命令行选项执行python脚本 [英] Using ProcessBuilder to execute a python script with command line options

查看:129
本文介绍了使用ProcessBuilder使用命令行选项执行python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了从Java执行python脚本(有几个命令行参数),我试图使用的是以下java代码

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

请注意,参数arg3采用参数值列表。

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

我面临的问题是我找不到通过的方法参数arg3的值列表。

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.

最好!

推荐答案

只需将它们作为单独的字符串添加到数组中,而不是将最后两个组合成 val_31 val_32

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",
       };

否则它将逃离 val_31 和 val_32 因为你告诉它它们只是一个参数。顺便提一下,你也可以使用 varargs 构造函数,如果需要,可以跳过必须创建一个数组:

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");

这篇关于使用ProcessBuilder使用命令行选项执行python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆