如何在子进程运行时从此代码打印进度?

2024-05-20 18:43:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: the代码fromimportrepasswordresultsort
1条回答
网友
1楼 · 发布于 2024-05-20 18:43:01

stdout=subprocess.PIPE阻止子进程打印到stdout,而是使用与bash中的how类似的^{}将其传递给result

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

将打印进度,但是

^{pr2}$

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

你想要的是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)

相关问题 更多 >