2016-03-06 66 views
0

我想讀取使用'rsync'同步文件的總數,並使用下面的Python代碼讀取值,我得到以下輸出。我應該修改哪些代碼來獲取所需的輸出如何統計使用rsync同步的文件總數?

輸出

b'10'

所需的輸出


CMD

rsync -nvaz --delete --stats [email protected]:/www/ . | ./awk.sh 

awk.sh

awk '\ 
BEGIN {count = 0} 
    /deleting/ {if (length($1) > 0) ++count} \ 
    /Number of regular files transferred:/{count += $6} \ 
END \ 
    { 
    printf "%d",count 
    }' 

的Python

subprocess.check_process(cmd, shell=True, stdout=False) 
+0

'回聲 「b'10' 」 | tr -cd'0-9 \ n''? – Cyrus

+0

即使在'tr -cd'0-9 \ n'之後,輸出也是**字節**,所以我將它們解碼爲** utf-8 ** –

回答

0

解碼輸出到UTF-8,然後解析使用正則表達式

o = subprocess.check_output(cmd, shell=True) 
g = re.search(r'count=(\d+)', o.decode("utf-8"), re.M|re.I) 
0

awk腳本只是尋找包含字符串的一行,然後打印。由於你的python腳本需要讀取stdout來獲取該值,所以你可以放棄腳本並堅持使用python。隨着Popen對象就可以讀取線標準輸出線

import subprocess 

# for test... 
source_dir = 'test1/' 
target_dir = 'test2/' 

count = 0 
proc = subprocess.Popen(['rsync', '-nvaz', '--delete', '--stats', 
    source_dir, target_dir], 
    stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
for line in proc.stdout: 
    if line.startswith(b'Number of regular files transferred:'): 
     count = int(line.split(b':')[1]) 
proc.wait() 
print(count) 
+0

我想保持代碼模塊化,因此分開** awk.sh **文件 –