python - 如何确定传递给命令行的字符串子进程?

标签 python windows subprocess

在 Windows 上,您通过传递字符串参数列表进行子进程调用,然后将其重新格式化为单个字符串以调用相关命令。它通过文档中概述的一系列规则来做到这一点 here .

On Windows, an args sequence is converted to a string that can be parsed using the following rules (which correspond to the rules used by the MS C runtime):

  1. Arguments are delimited by white space, which is either a space or a tab.
  2. A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument.
  3. A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark.
  4. Backslashes are interpreted literally, unless they immediately precede a double quotation mark.
  5. If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule

然而在实践中这可能很难做到正确,因为不清楚字符串是如何被解释的。在弄清楚如何正确格式化命令时可能会反复试验。

有没有一种方法可以确定子进程将制定什么字符串?这样我就可以检查它并确保它被正确地表述,并且比仅仅记录命令的列表形式更好地记录它。

最佳答案

我深入研究了实际的子流程模块并在其中找到了答案。有一个名为 list2cmdline 的函数,它用于获取传递给 Popen 的列表并将其转换为单个命令行参数字符串。只需使用列表调用它即可获得我需要的结果:

import subprocess

name = "Monty Python's Flying Circus"
path = r"C:\path\to\files"
subprocess.list2cmdline(["file.py", name, path])
# 'file.py "Monty Python\'s Flying Circus" C:\\path\\to\\files'

关于python - 如何确定传递给命令行的字符串子进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39081535/

相关文章:

python - 使用 Python 子进程在 stdout 上捕获 C 程序的输出?希望吗?

javascript - 在 Python 中复制 Javascript 按位运算

python - 从 Python 读取 FoxPro DBF 文件的最简单方法是什么?

python - crontab 自动 python 脚本不会上传到 dropbox

c# - 如何防止控件更改 Z 顺序?

c# - Windows 服务打印 PDF

python - PyCharm 无法访问/usr/lib/和/usr/bin/中的文件

windows - 在运行时确定弹出提示消息 (THintInfo::HintStr) 的大小

python - 将 find 命令的输出转换为 python 中的字符串数组

python - Python中的子进程执行两个任务?