将stdout保存到doctest中的变量中

时间:2014-01-06 13:34:39

标签: python doctest

我有一个doctest,我想将我遇到的命令保存到变量中,以便在另一个函数中使用它

   >>> sh("git finish", return_output=True).split("#")[1].split(":")[0]
   (here comes an int i want to save, say 900)

sh是一个看起来像这样的命令行函数

# short alias for check_output
def sh(cmd, return_output=False):
    from subprocess import call
    open('/dev/shm/fail_output', 'w').close()
    with open('/dev/shm/fail_output', 'a+') as output:
        call(cmd, stderr=output, stdout=output, shell=True)
    with open('/dev/shm/fail_output', 'r') as output:
        if return_output:
            return output.read()
        print output.read()

return locals()

1 个答案:

答案 0 :(得分:2)

您可以使用popen而不是调用来获取命令的输出:

output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]

有关subprocess documentation page

的更多信息
相关问题