【问题标题】:How can I have subprocess or Popen show the command line that it has just run?如何让 subprocess 或 Popen 显示它刚刚运行的命令行?
【发布时间】:2015-12-18 17:21:46
【问题描述】:

目前,我有一个类似于以下内容的命令:

my_command = Popen([activate_this_python_virtualenv_file, \
    "-m", "my_command", "-l", \
    directory_where_ini_file_for_my_command_is + "/" + my_ini_file_name], \
    stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=False,
    universal_newlines=False, cwd=directory_where_my_module_is)

我已经弄清楚如何访问和处理输出,处理subprocess.PIPE,并让 subprocess 做一些其他巧妙的技巧。

但是,the standard Python documentation for subprocess 没有提到获取实际命令行的方法,因为 subprocess.Popen 将其从参数组合到 Popen 构造函数中,这对我来说似乎很奇怪。

例如,可能是my_command.get_args() 或类似的东西?

只是在Popen 中运行命令行应该很容易吗?

我可以自己将参数放在一起,而无需访问命令subprocessPopen 一起运行,但如果有更好的方法,我想知道。

【问题讨论】:

    标签: linux python-3.x subprocess popen


    【解决方案1】:

    它是在 Python 3.3 中添加的。根据docs

    以下属性也可用:

    Popen.args args 参数,因为它被传递给 Popen - 一个序列 程序参数或单个字符串。

    3.3 版中的新功能。

    所以示例代码是:

    my_args_list = []  # yourlist
    p = subprocess.Popen(my_args_list)
    assert p.args == my_args_list
    

    【讨论】:

    • // ,这实际上会列出它运行的完整命令吗?例如,我可以将结果复制到兼容的 bash 终端并让它工作吗?
    猜你喜欢
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-07
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    相关资源
    最近更新 更多