【问题标题】:Python subprocess call rsyncPython子进程调用rsync
【发布时间】:2014-03-31 08:20:25
【问题描述】:

我正在尝试为文件夹中的每个文件夹运行 rsync。

__author__ = 'Alexander'
import os
import subprocess

root ='/data/shares'
arguments=["--verbose", "--recursive", "--dry-run", "--human-readable", "--remove-source-files"]
remote_host = 'TL-AS203'

for folder in os.listdir(root):
    print 'Sync Team ' + folder.__str__()

    path = os.path.join(root,folder, 'in')
    if os.path.exists(path):
        folder_arguments = list(arguments)
        print (type(folder_arguments))
        folder_arguments.append("--log-file=" + path +"/rsync.log")
        folder_arguments.append(path)
        folder_arguments.append("transfer@"+remote_host+":/data/shares/"+ folder+"/out")
        print "running rsync with " + str(folder_arguments)
        returncode = subprocess.call(["rsync",str(folder_arguments)])
        if returncode == 0:
            print "pull successfull"
        else:
            print "error during rsync pull"
    else:
        print "not a valid team folder, in not found"

如果我运行它,我会得到以下输出:

Sync Team IT-Systemberatung
<type 'list'>
running rsync with ['--verbose', '--recursive', '--dry-run', '--human-readable', '--remove-source-files', '--log-file=/data/shares/IT-Systemberatung/in/rsync.log', '/data/shares/IT-Systemberatung/in', 'transfer@TL-AS203:/data/shares/IT-Systemberatung/out']
rsync: change_dir "/data/shares/IT-Systemberatung/['--verbose', '--recursive', '--dry-run', '--human-readable', '--remove-source-files', '--log-file=/data/shares/IT-Systemberatung/in/rsync.log', '/data/shares/IT-Systemberatung/in', 'transfer@TL-AS203:/data/shares/IT-Systemberatung" failed: No such file or directory (2)
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1040) [sender=3.0.4]
error during rsync pull
Sync Team IT-Applikationsbetrieb
not a valid team folder, in not found
transfer@INT-AS238:/data/shares/IT-Systemberatung

如果我使用这些参数从 bash 手动启动 rsync,一切正常。我也尝试了 shell=true 但结果相同。

【问题讨论】:

    标签: python rsync


    【解决方案1】:

    你需要做的:

    returncode = subprocess.call(["rsync"] + folder_arguments)
    

    在列表上调用str() 将返回python 列表的字符串表示形式,这不是您想要作为参数传递给rsync 的字符串表示形式

    【讨论】:

    • 谢谢,这解决了我的问题!我不明白为什么我需要使用 ((["rsync"] + folder_arguments) 代替 (["rsync"] , folder_arguments) ?
    • subprocess.call 需要一个完整的命令行列表。 + 运算符将两个列表合并为一个列表。由于 folder_arguments 已经是一个列表,只需将其附加到仅包含“rsync”的列表中。所以结果列表看起来像:["rsync", "--verbose", "--recursive",...]
    【解决方案2】:

    你做了一个os.chdir(os.path.join(root,folder)),但永远不会回去。

    为了正确恢复对下一个文件夹的操作,您应该记住最后一个 os.getpwd() 并返回到它,或者在一个循环运行结束时执行 os.chdir('..')

    【讨论】:

    • 对不起,是代码的剩余部分,不要再使用 os.chdir
    猜你喜欢
    • 2016-04-06
    • 1970-01-01
    • 2012-12-25
    • 2020-03-22
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 2015-07-18
    • 2013-06-25
    相关资源
    最近更新 更多