gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 10:04:08 26 4
gpt4 key购买 nike

在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com