Python 子进程调用 rsync

1 投票
2 回答
4001 浏览
提问于 2025-04-18 00:38

我想对一个文件夹里的每个子文件夹运行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,但结果还是一样。

2 个回答

0

你用了一条命令 os.chdir(os.path.join(root,folder)) 来切换到一个文件夹,但之后没有再回到之前的文件夹。

为了在下一个文件夹继续操作,你应该记住上一个文件夹的位置 os.getpwd(),然后再返回去,或者在每次循环结束时直接用 os.chdir('..') 回到上一级文件夹。

1

你需要做的是:

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

对一个列表使用 str() 函数会得到这个列表的字符串表示形式,但这并不是你想要传给 rsync 的参数。

撰写回答