Python 解析子进程输出

1 投票
2 回答
1194 浏览
提问于 2025-05-01 16:47

我正在尝试保存

git remote show origin 

的输出,使用

  tempf = open('.tmp', 'w+')
  tempf2 = open('.tmp2', 'w+')
  subprocess.Popen(["git", "remote", "show", "origin"], stdout=tempf, stderr=tempf2)
  tempf.close()
  tempf2.close()
  output = open('.tmp', 'r')
  gitoutput = output.read()

,然后用正则表达式来解析这个输出。

但是,上面的代码总是返回Nonegitoutput

我是不是漏掉了什么?我有点困惑,因为使用.seek(0)并没有改变输出,而运行cat .tmp却能显示正确的内容。

补充说明:stderr也被捕获了(stderr=tempf2),但是这些内容被丢弃了,因为在运行脚本时,git服务器会在命令行上产生一些不需要的输出。

暂无标签

2 个回答

0

试试这样做

import subprocess
child = subprocess.Popen(["git", "remote", "show", "origin"], stdout=subprocess.PIPE,shell=True)
msg,err = child.communicate()
print msg
print err

这里的 communicate 会返回一个 tuple,里面包含了 outputerror message,也就是 (stdoutdata, stderrdata)

1

使用 .wait() 和 Popen

import subprocess
with open('.tmp', 'w+') as tempf,  open('.tmp2', 'w+') as tempf2:
    proc  = subprocess.Popen(["git", "remote", "show", "origin"], stdout=tempf, stderr=tempf2)
    proc.wait()
    tempf.seek(0)
    gitoutput = tempf.read()
print(gitoutput)

或者直接使用 check_call

with open('.tmp', 'w+') as tempf,  open('.tmp2', 'w+') as tempf2:
    proc  = subprocess.check_call(["git", "remote", "show", "origin"], stdout=tempf, stderr=tempf2)
    tempf.seek(0)
    gitoutput = tempf.read()
print(gitoutput)

撰写回答