首页 > 解决方案 > 连续获取输出:在python脚本中调用rsync info=progress2

问题描述

我正在用 popen 调用 rsync 并且输出没有像在普通 linux 中那样在我的 web 应用程序的 python 脚本中连续打印出来。我正在尝试将一个目录上的所有文件复制到另一个目录(大量副本)。我想使用从输出更改中收到的进度数字来最终创建/更新我在我的 Web 应用程序中拥有的进度条。我想要的是整个副本的总进度,所以我会在我的 rsync 命令中使用 --info=progress2 。我也试过:

while True:
        line = self.proc.stdout.readline()
        if line != '':
            # the real code does filtering here
            print("test:", line.rstrip())
        else:
            break

但这一直等到最后才打印 test: b'' 我认为问题在于 while 循环提取数据或我如何使用不同的类将其打印到控制台。

使用此 --info=progress2 的信息不多,因为它是一个相对较新的更新。

这是我的代码。

import subprocess
import logging
import sys
import os
import replicator.dfp.rep_utils as ru


class SyncProcessor(object):
    def __init__(self, src, dest):
        self.src = src
        self.dest = dest
        self.proc = None
        self.callback = None
        log_file = "sync-{}-{}.log".format(self.src, self.dest)
        self.sync_logger = ru.setup_logger(__file__, log_file, level=logging.DEBUG)

    def add_sync_callback(self, cb):
        self.callback = cb

    def run(self):
        print("Syncing Drive "+ str(self.src.driveNum) + " to Drive " + str(self.dest.driveNum))
        rsync_cmd = "sudo rsync -ah --info=progress2 --delete --stats /media/drive{}/ /media/drive{}".format(self.src.driveNum, self.dest.driveNum)
        self.proc = subprocess.Popen(rsync_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        while self.proc.poll() is None:
            output = self.proc.stdout.readline()
            if output == '':
                break
            if output:
                print("OUTPUT DECODE: " + output.decode("utf-8")
                #self.sync_logger.info(output.decode())
                self.callback.update(output.decode())
        print("<< Finished Syncing >>")
        #self.sync_logger.debug("<< Finished Syncing >>")
        rc = self.proc.poll()
        #self.sync_logger.debug("Return code: {}".format(rc))
        os.system("sync")
        return rc

    def communicate(self):
        return self.proc.communicate()

class Progress(object):
    """Callback to report progress of a SyncProcessor"""
    def __init__(self, src, dest, out=sys.stdout):
        self.src = src
        self.dest = dest
        self.out = out

    def update(self, data):
        line = "From Progress({}-{}) -> {}"
    self.out.write(line.format(self.src, self.dest, data))

标签: pythonlinuxsubprocessrsyncpopen

解决方案


所以我意识到百分比从 0-100% 的整个变化被视为一行,因为它被 \r 而不是 \n 分解

self.proc.stdout.readline()

因此这条线只有在进程达到 100% 后才会激活

我将它切换到 self.proc.stdout.readline(80) ,它每 80 个字符打印一次,让我更新百分比。但是,由于整个行的长度都在变化,我正在寻找一种更好的方法来做到这一点


推荐阅读