连续获取输出:rsync info =在Python脚本中调用progress2

问题描述 投票:-1回答:1

我正在使用popen调用rsync,输出不会在我的Web应用程序的python脚本中连续打印,就像在普通的linux中一样。我正在尝试将一个目录中的所有文件复制到另一个目录(大量复制)。我想使用从输出更改中收到的进度数来最终创建/更新我在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

但是等到最后只打印测试: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))
python linux subprocess rsync popen
1个回答
0
投票

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

self.proc.stdout.readline()

因此该行仅在过程达到100%后激活

我把它切换到self.proc.stdout.readline(80),它打印出来的每80个字符给我更新的百分比。然而,由于整个线路的长度变化,我正在寻找更好的方法来做到这一点

© www.soinside.com 2019 - 2024. All rights reserved.