2011-07-27 114 views
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 \」'一樣逃脫它們。但是這也行不通。當文件名或目錄中出現空格時,我需要雙引號。

我錯過了什麼?

回答

4

是的雙引號是問題,不要逃避它們,只是放下它們。

它們只是在shell上需要阻止shell擴展。

另外:如果你逃避他們,你已經證明的方式,他們才躲過蟒水平,它是沒有意義的,因爲雙引號被自動單引號內逃脫

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

它應該是

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

我剛剛回答我自己的問題,它可以用空格排除文件/文件夾而不使用雙引號,即'--exclude =%s',但你擊敗了我:)。接受,謝謝 – jelloir

相關問題