带有等号和空格的 Python 子进程参数 [英] Python subprocess argument with equal sign and space

查看:40
本文介绍了带有等号和空格的 Python 子进程参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 subprocess.check_output 运行命令而不使用 shell=True 关键字参数.我的命令是这样的:

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'])

这篇关于带有等号和空格的 Python 子进程参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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