Python的解析子输出
问题描述:
我想的Python的解析子输出
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()
后来解析与正则表达式的输出。
但是,上面的代码一直返回None
为gitoutput
。
有什么,我失踪?我很困惑,因为申请.seek(0)
不会改变输出并且运行cat .tmp
显示正确的内容。
编辑:stderr
也被捕获(stderr=tempf2
),并在运行脚本时git服务器产生不需要的输出到命令行。
答
使用.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)
答
尝试这样
import subprocess
child = subprocess.Popen(["git", "remote", "show", "origin"], stdout=subprocess.PIPE,shell=True)
msg,err = child.communicate()
print msg
print err
这里communicate
将返回包含一个tuple
的output
和error message
即(stdoutdata,stderrdata)
+0
任何我失误的原因??? – Hackaholic 2014-11-05 01:47:46
你可以试试'subprocess.check_call'而不是 – 2014-11-05 00:16:18