2014-03-31 116 views
0

我試圖爲文件夾中的每個文件夾運行rsync。Python子進程調用rsync

__author__ = 'Alexander' 
import os 
import subprocess 

root ='/data/shares' 
arguments=["--verbose", "--recursive", "--dry-run", "--human-readable", "--remove-source-files"] 
remote_host = 'TL-AS203' 

for folder in os.listdir(root): 
    print 'Sync Team ' + folder.__str__() 

    path = os.path.join(root,folder, 'in') 
    if os.path.exists(path): 
     folder_arguments = list(arguments) 
     print (type(folder_arguments)) 
     folder_arguments.append("--log-file=" + path +"/rsync.log") 
     folder_arguments.append(path) 
     folder_arguments.append("[email protected]"+remote_host+":/data/shares/"+ folder+"/out") 
     print "running rsync with " + str(folder_arguments) 
     returncode = subprocess.call(["rsync",str(folder_arguments)]) 
     if returncode == 0: 
      print "pull successfull" 
     else: 
      print "error during rsync pull" 
    else: 
     print "not a valid team folder, in not found" 

如果我運行此我得到以下輸出:

Sync Team IT-Systemberatung 
<type 'list'> 
running rsync with ['--verbose', '--recursive', '--dry-run', '--human-readable', '--remove-source-files', '--log-file=/data/shares/IT-Systemberatung/in/rsync.log', '/data/shares/IT-Systemberatung/in', '[email protected]:/data/shares/IT-Systemberatung/out'] 
rsync: change_dir "/data/shares/IT-Systemberatung/['--verbose', '--recursive', '--dry-run', '--human-readable', '--remove-source-files', '--log-file=/data/shares/IT-Systemberatung/in/rsync.log', '/data/shares/IT-Systemberatung/in', '[email protected]:/data/shares/IT-Systemberatung" failed: No such file or directory (2) 
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1040) [sender=3.0.4] 
error during rsync pull 
Sync Team IT-Applikationsbetrieb 
not a valid team folder, in not found 
[email protected]:/data/shares/IT-Systemberatung 

如果我手動從這些參數的bash啓動rsync的,一切工作正常。我也嘗試了shell = true,但結果相同。

回答

1

你需要做的:

returncode = subprocess.call(["rsync"] + folder_arguments) 

名單上調用str()將返回Python列表的字符串表示形式這是不是你想作爲參數傳遞給rsync

+0

謝謝,這解決了我的問題! ([「rsync」] + folder_arguments)而不是([「rsync」],folder_arguments)? –

+0

'subprocess.call'需要一個完整的命令行列表,'+因爲folder_arguments已經是一個列表,只需將它附加到僅包含「rsync」的列表中,那麼結果列表如下所示:[「rsync」,「--verbose」, - 遞歸」,...] – spinlok

0

你做了一個os.chdir(os.path.join(root,folder)),但永遠不會回去。

爲了正確地恢復下一個文件夾的操作,您應該記住最後一個os.getpwd()並返回到它,或者在一次循環運行結束時執行os.chdir('..')

+0

對不起什麼,是代碼中的剩餘部分,不再使用os.chdir –