具有等号和空格的 Python 子进程参数

2022-01-18 00:00:00 python shell subprocess

问题描述

我试图在不使用 shell=True 关键字参数的情况下运行带有 subprocess.check_output 的命令.我的命令是这样的:

I am trying to run a command with subprocess.check_output without using shell=True keyword argument. My command is this:

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 becomes to this(white space after =):

command --parameter= "something with spaces"

有没有不使用 shell=True


解决方案

以下是你需要知道的:

空格用于分隔 shell 命令行上的参数.但是,如果您不使用 shell,则不需要转义空格.空格可以至少以两种方式转义(据我所知):使用引号(单引号或双引号)和反斜杠.

Spaces are used for separating arguments on the shell command line. However, if you are not using shell, you don't need to escape spaces. Spaces can be escaped at least two ways ( that I know of ): With quotes ( either single or double ) and the backslash .

当您将数组传递给 subprocess.check_output() 时,您已经将命令划分为子进程的参数.因此,您不需要带空格的东西"周围的引号.也就是说,您不需要转义空格.相反,正如您在结果片段中显示的那样,引号被完全视为引号:

When you pass an array to subprocess.check_output() you are already dividing the command into parameters for the subprocess. Thus, you don't need the quotes around "something with spaces". That is, you don't need to escape the spaces. Rather, the quotes are being taken quite literally as quotes as you have shown with your result snippet:

command "--parameter="something with spaces""

现在我希望你已经猜到正确答案是什么了.前方剧透:

By now I hope you have guessed what the right answer is. Spoiler ahead:

subprocess.check_output(['command', '--parameter=something with spaces'])

相关文章