Python:rsync排除在脚本中不起作用,适用于bash shell

时间:2011-07-27 13:11:59

标签: python subprocess quotes rsync

下面是我用来测试问题的脚本。

通过subprocess.check_call运行rsync命令不能排除从exclude变量中获取的文件。

我从Python打印命令的结果,编辑它然后直接在bash shell中运行它作为比较,并且在使用Python时它无法排除我的排除。

#!/usr/bin/env python3.1

import subprocess

exclude = 'exclude_me_dir, exclude_me_file.txt'
source_path = '/tmp/source'
path_to_backup_file_name = '/tmp/destination'
engine_options = '-axh --delete --delete-excluded'

def rsync_backup(source_path, path_to_backup_file_name, exclude, engine_options):
    exclusions = ['--exclude="%s"' % x.strip() for x in exclude.split(',')]
    rsync_command = ['rsync'] + exclusions + engine_options.split() + [source_path + '/', path_to_backup_file_name]
    print(rsync_command)
    return subprocess.check_call(rsync_command)


rsync_backup(source_path, path_to_backup_file_name, exclude, engine_options)

这是Python脚本的输出并直接运行rsync命令。

> pwd
/root
> ls /tmp/source/
exclude_me_dir/  exclude_me_file.txt  file1.txt  folder1/
> /tmp/rsynctest.py
['rsync', '--exclude="exclude_me_dir"', '--exclude="exclude_me_file.txt"', '-axh', '--delete', '--delete-excluded', '/tmp/source/', '/tmp/destination']
> ls /tmp/destination/
exclude_me_dir/  exclude_me_file.txt  file1.txt  folder1/
> rsync --exclude="exclude_me_dir" --exclude="exclude_me_file.txt" -axh --delete --delete-excluded /tmp/source/ /tmp/destination
> ls /tmp/destination/
file1.txt  folder1/

N.B。当我即将发布这个时,我发现问题似乎是'--exclude =“file”'中的双引号,好像我删除了它有效。我尝试将它们转义为'--exclude = \“file \”'。但这也不起作用。在文件名或目录中出现空格时,我需要双引号。

我错过了什么?

1 个答案:

答案 0 :(得分:4)

是的,双引号是问题,不要逃避它们,只是放弃它们。

它们只是在shell上需要阻止shell扩展。

此外:如果你以你显示的方式逃脱它们,它们只会在python级别上被转义,因为它没有任何意义,因为双引号会在单引号内自动转义

In [2]: '\"foo\"'
Out[2]: u'"foo"'

应该是

In [3]: '\\"foo\\"'
Out[3]: u'\\"foo\\"'