如评论中所述,subprocess
附带(未在文档页面中记录)list2cmdline
将参数列表转换为单个字符串。根据源文档,list2cmdline
主要在 Windows 上使用:
在 Windows 上:Popen 类使用 CreateProcess() 来执行子程序,该程序对字符串进行操作。如果 args 是一个序列,它将使用 list2cmdline 方法转换为字符串。请注意,并非所有 MS Windows 应用程序都以相同的方式解释命令行:list2cmdline 是为使用与 MS C 运行时相同规则的应用程序设计的。
不过,它在其他操作系统上非常有用。
编辑
如果您需要反向操作(即,将命令行拆分为正确标记化参数的列表),您将需要使用该shlex.split
函数,如subprocess
.
>>> help(subprocess.list2cmdline)
Help on function list2cmdline in module subprocess:
list2cmdline(seq)
Translate a sequence of arguments into a command line
string, using the same rules as 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 3.