2016-06-22 67 views
1

閱讀過濾規則手冊頁,看着這裏後:Using Rsync filter to include/exclude filesRsync的過濾器在Python循環

我不明白,爲什麼下面的代碼無法正常工作。

import subprocess, os 
from ftplib import FTP 

ftp_site = 'ftp.ncbi.nlm.nih.gov' 
ftp = FTP(ftp_site) 
ftp.login() 
ftp.cwd('genomes/genbank/bacteria') 
dirs = ftp.nlst() 

for organism in dirs: 
    latest = os.path.join(organism, "latest_assembly_versions") 
    for path in ftp.nlst(latest): 
     accession = path.split("/")[-1] 
     fasta = accession+"_genomic.fna.gz" 
     subprocess.call(['rsync', 
         '--recursive', 
         '--copy-links', 
         #'--dry-run', 
         '-vv', 
         '-f=+ '+accession+'/*', 
         '-f=+ '+fasta, 
         '-f=- *', 
         'ftp.ncbi.nlm.nih.gov::genomes/genbank/bacteria/'+latest, 
         '--log-file=scratch/test_dir/log.txt', 
         'scratch/' + organism]) 

我也試過'--exclude=*[^'+fasta+']'儘量排除不中latest/*匹配fasta代替-f=- *

對於每個目錄path文件,我想這完全匹配fasta文件。目錄latest/path中始終只有一個文件fasta

編輯:我與的rsync版本3.1.0測試這一點,並已經看到了不兼容問題與早期版本。

這裏是工作的代碼,你應該能夠將其粘貼到Python解釋器得到的結果中的鏈接「試運行」,這將不會下載任何東西到你的機器:http://pastebin.com/0reVKMCgftp.ncbi.nlm.nih.gov::genomes/genbank/bacteria/'+latest下得到的一切,這不是我想要的。如果我運行該腳本與'-f=- *'取消註釋,它沒有得到任何東西,這似乎違背這裏Using Rsync filter to include/exclude files

+0

你確定你可以通過FTP使用'rsync'嗎?:http://serverfault.com/questions/24622/how-to-use-rsync-over -ftp –

+0

是的,我確定。我有一個類似的腳本工作得很漂亮,直到我意識到我得到的一些文件(根據我的過濾器)是我不想要的文件。 – truthling

+0

嗯,你可以發佈工作片段,以便我們可以得到一個示例輸出,然後進一步闡明你想要過濾的內容? –

回答

0

答案這包含我需要解決我的問題的信息的rsync手冊頁的一部分:

請注意,當使用--recursive(-r)選項(由-a暗示)時,每個 路徑的每個子組件都會從上到下訪問,因此包含/排除模式會遞歸應用於每個子組件 - nent的全名(例如包括「/ foo/bar/baz」,排除子組件「/ foo」和「/ foo/bar」不得爲 )。當rsync發現 文件發送時,排除模式實際上使目錄遍歷階段短路。如果某個模式排除了特定的父目錄,則它可能會導致更深入的包含,因爲rsync並未通過層次結構的排除部分下降。這是 使用尾隨'*'規則時尤爲重要。舉例來說,這是不行的:

+ /一些/路徑/這個文件 - 將 - 不被發現的

+ /文件中,包括

- *

由於「*」規則排除了父目錄「some」,因此rsync從不會訪問「some」或「some/path」目錄中的任何 文件。一種解決方案是通過使用單個規則來請求包含 層級中的所有目錄:「+ * /」(將其放置在「 - *」規則之前的某個位置),並且每個haps使用--prune-空dirs選項。另一種解決方案是爲所有需要訪問的父級代表添加特定的包含規則。舉例來說,這套規則正常工作:

+ /一些/

+ /一些/路徑/

+ /一些/路徑/這個文件,被發現的

+ /文件還-包括

- *

幫我寫了下面的代碼:

def get_fastas(local_mirror="scratch/ncbi", bacteria="Escherichia_coli"): 
     ftp_site = 'ftp.ncbi.nlm.nih.gov' 
     ftp = FTP(ftp_site) 
     ftp.login() 
     ftp.cwd('genomes/genbank/bacteria') 
     rsync_log = os.path.join(local_mirror, "rsync_log.txt") 
     latest = os.path.join(bacteria, 'latest_assembly_versions') 
     for parent in ftp.nlst(latest)[0:2]: 
       accession = parent.split("/")[-1] 
       fasta = accession+"_genomic.fna.gz" 
       organism_dir = os.path.join(local_mirror, bacteria) 
       subprocess.call(['rsync', 
           '--copy-links', 
           '--recursive', 
           '--itemize-changes', 
           '--prune-empty-dirs', 
           '-f=+ '+accession, 
           '-f=+ '+fasta, 
           '--exclude=*', 
           'ftp.ncbi.nlm.nih.gov::genomes/genbank/bacteria/'+parent, 
           organism_dir]) 

原來'-f=+ '+accession,不尾隨/後,用*工作。雖然它確實可以在只有尾部的情況下工作/沒有*