gpt4 book ai didi

python - 当子进程运行时,如何打印此代码的进度?

转载 作者:太空宇宙 更新时间:2023-11-03 19:04:27 24 4
gpt4 key购买 nike

上面的代码仅在代码执行完成时显示 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)

最佳答案

stdout=subprocess.PIPE 阻止子进程打印到 stdout,而是使用 communicate 将其传递到 result类似于 bash 中的方式

sshpass -[args] rsync [source] [dest]

将打印进度但是

sshpass -[args] rsync [source] [dest] | sort

在该过程完成之前不会打印任何内容。

您想要的是 tee stdout。看here 。根据这些答案,您可以执行以下操作:

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

关于python - 当子进程运行时,如何打印此代码的进度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15104415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com