3
下面是我用來測試問題的腳本。Python:rsync排除不在腳本中工作,在bash shell中工作
通過subprocess.check_call運行rsync命令無法排除從排除變量中獲取的文件。
我從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 \」'一樣逃脫它們。但是這也行不通。當文件名或目錄中出現空格時,我需要雙引號。
我錯過了什麼?
我剛剛回答我自己的問題,它可以用空格排除文件/文件夾而不使用雙引號,即'--exclude =%s',但你擊敗了我:)。接受,謝謝 – jelloir