如何获得生成的子进程命令字符串

Rab*_*ski 6 python subprocess

我有Python子进程调用,它们被格式化为一个参数序列(subprocess.Popen(['ls','-l'])而不是单个字符串(即subprocess.Popen('ls -l'))).

当像我一样使用顺序参数时,有没有办法获得发送到shell的结果字符串(用于调试目的)?

一种简单的方法是将自己的所有论点加在一起.但我怀疑这在所有情况下都与子进程的作用相同,因为使用序列的主要原因是"允许模块处理任何所需的转义和引用参数".

Pie*_* GM 11

正如评论中所提到的那样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.
Run Code Online (Sandbox Code Playgroud)