yoz*_*zel 4 python shell subprocess
我试图在subprocess.check_output不使用shell=True关键字参数的情况下运行命令.我的命令是这样的:
command --parameter="something with spaces"
Run Code Online (Sandbox Code Playgroud)
有了这个:
subprocess.check_output(['command', '--parameter="something with spaces"'])
Run Code Online (Sandbox Code Playgroud)
命令变为:
command "--parameter=\"something with spaces\""
Run Code Online (Sandbox Code Playgroud)
有了这个:
subprocess.check_output(['command', '--parameter=', 'something with spaces'])
Run Code Online (Sandbox Code Playgroud)
命令变为此(后面的空格=):
command --parameter= "something with spaces"
Run Code Online (Sandbox Code Playgroud)
有没有正确的方法可以不使用 shell=True
这是你需要知道的:
空格用于在shell命令行上分隔参数.但是,如果您不使用shell,则无需转义空格.空间可以至少以两种方式转义(我知道):带引号(单引号或双引号)和反斜杠.
将数组传递给subprocess.check_output()时,您已将命令划分为子进程的参数.因此,您不需要围绕"带空格的东西"的引号.也就是说,您不需要逃离空间.相反,引号与字面意思一样,就像你在结果片段中显示的那样:
command "--parameter=\"something with spaces\""
Run Code Online (Sandbox Code Playgroud)
到现在为止,我希望你已经猜到了正确答案是什么.扰乱前方:
subprocess.check_output(['command', '--parameter=something with spaces'])
Run Code Online (Sandbox Code Playgroud)