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

Python subprocess argument with equal sign and space(具有等号和空格的 Python 子进程参数)
本文介绍了具有等号和空格的 Python 子进程参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在不使用 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'])

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)