等号和空格的Python子流程参数
问题内容:
我试图在subprocess.check_output
不使用shell=True
关键字参数的情况下运行命令。我的命令是这样的:
command --parameter="something with spaces"
有了这个:
subprocess.check_output(['command', '--parameter="something with spaces"'])
命令变为:
command "--parameter=\"something with spaces\""
并与此:
subprocess.check_output(['command', '--parameter=', 'something with spaces'])
命令变为以下(空格后=
):
command --parameter= "something with spaces"
有没有不使用它的正确方法 shell=True
问题答案:
这是您需要了解的内容:
空格用于在shell命令行上分隔参数。但是,如果您不使用外壳,则不需要转义空格。空格至少可以通过两种方式转义(据我所知):带引号(单引号或双引号)和反斜杠。
当您将数组传递给subprocess.check_output()时,您已经将命令划分为子流程的参数。因此,您不需要在“带有空格的东西”周围加上引号。也就是说,您不需要逃脱空格。相反,引号实际上就是引号,就像您在结果片段中显示的那样:
command "--parameter=\"something with spaces\""
到现在为止,我希望您已经猜到了正确的答案。剧透:
subprocess.check_output(['command', '--parameter=something with spaces'])