Python:rsync排除在脚本中不起作用,在bashshell中起作用
下面是我用来测试一个问题的脚本 通过subprocess.check_调用运行rsync命令无法排除从排除变量获取的文件 我从Python打印命令的结果,编辑它,然后在bashshell中直接运行它作为比较,在使用Python时它无法排除我的排除Python:rsync排除在脚本中不起作用,在bashshell中起作用,python,subprocess,quotes,rsync,Python,Subprocess,Quotes,Rsync,下面是我用来测试一个问题的脚本 通过subprocess.check_调用运行rsync命令无法排除从排除变量获取的文件 我从Python打印命令的结果,编辑它,然后在bashshell中直接运行它作为比较,在使用Python时它无法排除我的排除 #!/usr/bin/env python3.1 import subprocess exclude = 'exclude_me_dir, exclude_me_file.txt' source_path = '/tmp/source' path_
#!/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/
注意:当我即将发布这篇文章时,我发现问题似乎是'--exclude=“file”'中的双引号,就好像我删除了它们一样。我试着像这样转义'--exclude=\'file\''。但这也不起作用。当文件名或目录中出现空格时,我需要双引号
我遗漏了什么?是的,双引号是问题所在,不要逃避它们,直接扔掉它们 它们只是需要在外壳上,以阻止外壳膨胀 此外:如果按照所示的方式对它们进行转义,那么它们只会在python级别上进行转义,因为双引号会在单引号中自动转义
In [2]: '\"foo\"'
Out[2]: u'"foo"'
应该是
In [3]: '\\"foo\\"'
Out[3]: u'\\"foo\\"'
我正要回答我自己的问题,即不使用双引号就可以排除带有空格的文件/文件夹,即--exclude=%s,但您比我先解决了:)。接受,谢谢