2014-11-04 138 views
1

我想的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() 

後來解析與正則表達式的輸出。

但是,上面的代碼一直返回Nonegitoutput

有什麼,我失蹤?我很困惑,因爲申請.seek(0)不會改變輸出並且運行cat .tmp顯示正確的內容。

編輯:stderr也被捕獲(stderr=tempf2),並在運行腳本時git服務器產生不需要的輸出到命令行。

+0

你可以試試'subprocess.check_call'而不是 – 2014-11-05 00:16:18

回答

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) 
0

嘗試這樣

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

這裏communicate將返回包含一個tupleoutputerror message即(stdoutdata,stderrdata)

+0

任何我失誤的原因??? – Hackaholic 2014-11-05 01:47:46