2017-07-24 139 views
0

我正在嘗試獲取實時輸出以及完整輸出。我有下面的代碼輸出指令的實時輸出很好,但我還需要獲取完整的輸出,然後可以在電子郵件的形式發送,而無需中斷實時輸出使用子進程獲取實時輸出和全輸出

backup = subprocess.Popen("rsync ....", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
for line in iter(backup.stdout.readline, b''): 
    print(">>> " + line.rstrip()) 

我曾嘗試加入以下但它會導致實時輸出不顯示

output = backup.stdout.read() 

回答

1

爲什麼不沿途收集完整/完整輸出?

backup = subprocess.Popen("rsync ....", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
full = [] 
for line in iter(backup.stdout.readline, b''): 
    line = line.rstrip().decode('utf8') 
    print(">>>", line) 
    full.append(line) 

output = '\n'.join(full) 
print("full output:", output)