我有 Python 子进程调用,它们被格式化为一系列参数(如 subprocess.Popen(['ls','-l'])
而不是单个字符串(即 subprocess.Popen('ls -l')
).
当像我一样使用顺序参数时,有没有办法获取发送到 shell 的结果字符串(用于调试目的)?
一个简单的方法是我自己将所有论点结合在一起。但我怀疑这在所有情况下都与子进程所做的相同,因为使用序列的主要原因是 'allow[s] the module to take care of any required escaping and quoting of arguments' .
最佳答案
如评论中所述,subprocess
附带(未在文档页面中记录)list2cmdline
将参数列表转换为单个字符串。
根据源文档,list2cmdline
主要用于 Windows:
On Windows: the Popen class uses CreateProcess() to execute the child program, which operates on strings. If args is a sequence, it will be converted to a string using the list2cmdline method. Please note that not all MS Windows applications interpret the command line the same way: The list2cmdline is designed for applications using the same rules as the MS C runtime.
不过,它在其他操作系统上非常有用。
编辑
如果您需要反向操作(即,将命令行拆分为正确标记化参数的列表),您需要使用 shlex.split
函数,如 doc of 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.
关于python - 如何获取生成的子进程命令字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12130163/