如何在子进程运行时打印进度?
上面的代码只在执行完毕后显示rsync的进度。我想要在文件传输的过程中就实时显示进度。例如,当文件正在传输时,我希望能够一直看到进度。请问我该怎么做呢?
import re
import subprocess
def sort(rprogress):
'''This function extracts the percentage from the rsync progress and return strings of percentanges'''
progress1 = re.findall(r'\d+%', rprogress)
remove_duplicate = set(progress1) #Remove Duplicate percentage from list
remove_percent = [a.replace('%', '') for a in remove_duplicate] #Removes percentage
sorted_list = sorted(remove_percent, key=int) #Sort in ascending order
#result = ', '.join(map(lambda sorted_list: str(sorted_list) + '%', sorted_list)) #Adds the percentage
return sorted_list
source12 = 'sachet.adhikari@69.43.202.97:/home/sachet/my_files/ok.txt'
password = 'password'
destination = '/home/zurelsoft/files'
result = subprocess.Popen(['sshpass', '-p', password, 'rsync', '-avz', '--info=progress2', source12, destination],
stdout=subprocess.PIPE).communicate()[0]
print result
print sort(result)
1 个回答
2
使用 stdout=subprocess.PIPE
这个设置,可以让子进程不直接在屏幕上打印输出,而是把输出内容传递给 result
。这个过程有点像在 bash 中使用 communicate
的方式。
sshpass -[args] rsync [source] [dest]
在这种情况下,进度会被打印出来,但
sshpass -[args] rsync [source] [dest] | sort
在进程完成之前,什么都不会被打印。
如果你想要的是同时看到输出和保存输出,可以使用 tee
命令。具体的做法可以参考 这里。根据那些答案,你可以尝试这样做:
# Caution! untested code
result = []
process = subprocess.Popen(['sshpass', '-p', password, 'rsync', '-avz',
'--info=progress2', source12, destination],
stdout=subprocess.PIPE)
while process.poll() is None:
line = process.stdout.readline()
print line
result.append(line)
print sort(result)