Project needs to obtain the real-time progress of rsync backup, mainly using the Subprocess module of the pipeline function, online check is someone wrote this: Popen = subprocess. Popen ([' Ping ', ' www.baidu.com ', '-N ', ' 3 '], stdout = subprocess. PIPE) while True:print Popen.stdout.readline () to Subproces
The project needs to obtain the real-time progress of the rsync backup, mainly using the piping function of the subprocess module, which is written by someone on the Internet:
Popen = subprocess. Popen ([' Ping ', ' www.baidu.com ', '-N ', ' 3 '], stdout = subprocess. PIPE) while
True:
print Popen.stdout.readline ()
Used to subprocess. Popen method, the stdout parameter is positioned to subprocess. In pipe, this is OK for commands like ' ping ' because ping is printed on one line and can be obtained directly with ReadLine, but the progress of software like Rsync is refreshed in a row, the buffer showing progress is not released, So you can't go to school with ReadLine, or you have to wait until the whole program is finished. Check the manual and data, found that stdout can be defined to the file object, tried, can be resolved:
Import subprocess
Import sys
import time
import random
import OS
import re
if __name__ = ' __ Main__ ':
cmdline = []
cmdline.append (' rsync ')
Cmdline.append ('--progress ') cmdline.append ('/kvmdata/kvm/vm_winxp/winxp.img ') cmdline.append ('/root/winxp.img ') Tmpfile = "./tmp/%d.tmp"% random.randint (10000,99999) #临时生成一个文件 fpwrite = open (tmpfile, ' w ') process = Subpro Cess. Popen (cmdline,stdout = Fpwrite,stderr = subprocess.
PIPE); While true:fpread = open (tmpfile, ' R ') #这里又重新创建了一个文件读取对象, do not know why, with the above is not read out, change w+ also not lines = Fpread.readlines (
For line in Lines:print line if Process.poll (): break; Fpwrite.truncate () #此处清空文件, waiting to record the next output Progress Fpread.close () Time.sleep (3) fpwrite.close () error = Proc Ess.stderr.read () if not error = = None:print ' ERROR info:%s '% error Os.popen (' rm-rf%s '% tmpfile) #删除临 When file print ' finished '
This allows you to get the backup progress of rsync in real time. Title: Get the output of the shell command in real time with Python [rsync backup progress] This article link: http://www.maben.com.cn/archives/623.html reprint please indicate the source