【问题标题】:Simple python command to capture shell execution output? [duplicate]捕获shell执行输出的简单python命令? [复制]
【发布时间】:2012-08-22 13:27:02
【问题描述】:

可能重复:
Running shell command from python and capturing the output

当我想捕获 shell 执行输出时,我会这样做。

declare TAGNAME=`git describe --tags` 

简单。我在 Python 中寻找过这个,但它们中的大多数看起来都非常复杂。最简单的方法是什么?是的,我知道我可以创建一个函数,但我想知道预定义函数是否存在。

tagname = theFunc('git describe --tags')

【问题讨论】:

    标签: python shell capture


    【解决方案1】:

    试试:

    >>> import subprocess
    >>> tagname = subprocess.check_output('git describe --tags'.split())
    

    【讨论】:

    • 返回字符串需要调用.strip('\n')
    • @Eonil 为什么打电话给.strip('\n')?拥有\n 真的很重要吗?
    • @xiaomao 是的。因为我会将字符串传递给另一个 shell 命令。能得到意想不到的结果真是太好了。
    【解决方案2】:

    您应该看看subprocess 模块。您也可以使用它捕获命令的输出。手册页中有很多如何使用该模块的示例。

    例子:

    output=subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE,
        stderr=subprocess.PIPE).communicate()
    

    结果是从命令中捕获的带有 stdout 和 stderr 的元组。

    【讨论】:

      猜你喜欢
      • 2014-04-18
      • 2018-01-28
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      相关资源
      最近更新 更多