我有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'。
答案 0 :(得分:10)
如评论中所述,subprocess
附带(未在文档页面中记录)list2cmdline
,它将参数列表转换为单个字符串。
根据源文档,list2cmdline
主要用于Windows:
在Windows上:Popen类使用CreateProcess()来执行子级 程序,对字符串进行操作。如果args是一个序列,它将是 使用list2cmdline方法转换为字符串。请注意 并非所有MS Windows应用程序都解释命令行相同 方式:list2cmdline是为使用相同的应用程序而设计的 规则作为MS C运行时。
然而,它在其他操作系统上非常实用。
修改强>
如果您需要反向操作(即,将命令行拆分为正确标记化参数列表),您将需要使用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.