Python 如何获取生成的子流程命令字符串
我有一些Python子流程调用,它们被格式化为一系列参数(如Python 如何获取生成的子流程命令字符串,python,subprocess,Python,Subprocess,我有一些Python子流程调用,它们被格式化为一系列参数(如subprocess.Popen(['ls','-l')),而不是单个字符串(即subprocess.Popen('ls-l')) 当像我一样使用序列参数时,是否有方法获取发送到shell的结果字符串(用于调试目的) 一种简单的方法是自己将所有参数连接在一起。但我怀疑这在所有情况下都与子流程相同,因为使用序列的主要原因是为了。如注释中所述,子流程附带(未在文档页面中记录)list2cmdline将参数列表转换为单个字符串。 根据源文件,
subprocess.Popen(['ls','-l'))
,而不是单个字符串(即subprocess.Popen('ls-l')
)
当像我一样使用序列参数时,是否有方法获取发送到shell的结果字符串(用于调试目的)
一种简单的方法是自己将所有参数连接在一起。但我怀疑这在所有情况下都与子流程相同,因为使用序列的主要原因是为了。如注释中所述,
子流程
附带(未在文档页面中记录)list2cmdline
将参数列表转换为单个字符串。
根据源文件,list2cmdline
主要用于Windows:
在Windows上:Popen类使用CreateProcess()执行子进程
对字符串进行操作的程序。如果args是序列,则
使用list2cmdline方法转换为字符串。请注意
并非所有MS Windows应用程序对命令行的解释都相同
方式:list2cmdline是为使用相同
规则作为MS C运行时
尽管如此,它在其他操作系统上还是很有用的
编辑
如果需要反向操作(即,将命令行拆分为正确标记的参数列表),则需要使用shlex.split
函数,如中所示
subprocess
附带了一个list2cmdline
函数,可以将参数列表转换为一个字符串,同时考虑空格和引号。它对您有用吗?@Pierre:是的,这就是我要找的。我搜索了subprocess doc页面(我链接到的那一个页面),但不幸的是,它没有提到。如果你在回答中提出你的建议,我会将其标记为接受。在Unix/Linux上,没有“发送到shell的结果字符串”这样的东西。参数是单独发送的。字符串只在Windows上生成。@interjay:有趣,我不知道这一点。它如何“在其他操作系统上非常有用”如果报价规则与POSIX完全不同?
>>> 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.