2013-06-30 66 views
2

我想要打印而不是從bash命令中捕獲輸出(更接近實時比this post)。舉例來說,我有一個這樣的腳本:從子流程中實時打印stdout

from subprocess import Popen, PIPE, STDOUT 
cmd = 'rsync --rsh=ssh -rv thisdir/ servername:folder/' 
p = Popen(cmd.split() ,stdout=PIPE, stderr=STDOUT) 
output = p.communicate()[0] 
print output 

我想從rsync的印刷實時彷彿是從命令行rsyncing,而不是等待的過程來完成打印輸出文件傳輸的細節。

回答

4

嘗試這樣做是這樣的:

from subprocess import Popen, PIPE, STDOUT 
cmd = 'rsync --rsh=ssh -rv thisdir/ servername:folder/' 
p = Popen(cmd.split(), stdout=PIPE, stderr=STDOUT) 
for line in p.stdout: 
    print line 

注意,那p.stdout有硬編碼緩衝區(8192 bytes),如果你想立刻開始讀文件,試試這個:

for line in iter(p.stdout.readline,''): 
    print line 
1
import subprocess 
cmd = 'rsync --rsh=ssh -rv thisdir/ servername:folder/' 
subprocess.call(cmd, shell=True) 

(該shell=True paramater通過它傳遞給sh,讓sh分割字符串成令牌解釋字符串。)