【问题标题】:How to count number of files available in a directory recursively in Python using rsync?如何使用 rsync 在 Python 中递归地计算目录中可用文件的数量?
【发布时间】:2013-07-09 16:01:39
【问题描述】:

我想在 Python 中使用 rsync 递归地计算远程服务器路径中的文件数?我试过这样做:

def find_remote_files(source, password):
    cmdline = ['sshpass', '-p', password, 'rsync', '--recursive', source]
    with open(os.devnull, "w") as devnull:
        proc = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=devnull)
        try:
            for entry in proc.stdout:
                items = entry.strip().split(None, 4)
                if not items[0].startswith("d"):
                    yield lent(items[4])
            proc.wait()
        except:
            # On any exception, terminate process and re-raise exception.
            proc.terminate()
            proc.wait()
            raise

它适用于我的文件较少的情况。但是如果我有超过 3000 个文件,rsync 将需要很长时间才能将其存储在列表中并再次计算长度。这就是为什么,我想知道是否有一个 rsync 命令只是为了计算文件。

【问题讨论】:

    标签: python rsync python-2.6


    【解决方案1】:

    我会使用另一种方法来使用 Fabric,它是执行远程命令的绝佳工具。

    from fabric.api import run, env  
    env.host_string = 'example.org'
    output = run('find /tmp -type f | wc -l')
    num_files = int(output)
    

    现在您在变量num_files 中获得了文件数。我只是使用find 命令从目录/tmp 开始递归搜索文件,并用wc -l 计算返回的行数。

    【讨论】:

    • host_string = 'example.org'的用户名和密码应该放在哪里?
    • 只需查看有关fabric 的文档:docs.fabfile.org/en/1.6 - 您可以在命令行或fabfile 中提供主机和用户。不应使用密码,因为通常的方法是使用不带密码的 ssh 密钥。
    猜你喜欢
    • 2021-09-09
    • 1970-01-01
    • 2015-03-01
    • 1970-01-01
    • 2012-02-27
    • 2011-02-07
    • 1970-01-01
    • 2016-06-04
    • 2016-07-11
    相关资源
    最近更新 更多