我有一个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()
答案 0 :(得分:2)
您可以使用popen而不是调用来获取命令的输出:
output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
的更多信息