python - 如何获取生成的子进程命令字符串

标签 python subprocess

我有 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/

相关文章:

python - pandas,使用func pandas.Series.value_counts后如何获取索引?

python - 基于共享 key 组合数据帧

python - Popen子处理问题

python - 从 Python 调用 R 脚本不会在版本 4 中保存日志文件

Python subprocess.call() 为每个 stdout 和 stderr 行添加前缀

python - 使用属性装饰器的Python类中的属性行为

python - 使用Python结束外部程序

python - 如何根据用户输入从 python 模块打开列表

python - 使用子进程模块并行工作(多进程)

python - 如何在 Python 程序中正确使用 gdaladdo?