2017-05-30 49 views
0

在我的程序中,我使用shutil將文件複製到列表中的多臺計算機上。我想知道如果某臺計算機恰好關閉,最好的方法是給出錯誤並移到下一臺計算機上。如何使用shututil無法連接到計算機時發生錯誤

我的原代碼:

def copyfiles(servername): 
    # copy config to remote server 
    source = os.listdir("C:/Users/myname/Desktop/PythonUpdate/") # directory where original configs are located 
    destination = '//' + servername + '/c$/test/' # destination server directory 
    for files in source: 
     if files.endswith(".config"): 
      shutil.copy(files,destination) 

os.system('cls' if os.name == 'nt' else 'clear') 
array = [] 
with open("C:/Users/myname/Desktop/PythonUpdate/serverlist.txt", "r") as f: 
    for servername in f: 


     copyfiles(servername.strip()) 

我所試圖做的事:

def copyfiles(servername): 
    # copy config to remote server 
    source = os.listdir("C:/Users/myname/Desktop/PythonUpdate/") # directory where original configs are located 
    destination = '//' + servername + '/c$/test/' # destination server directory 
    for files in source: 
     if files.endswith(".config"): 
      try: 
       shutil.copy(files,destination) 
      except: 
       print (" //////////////////////////////////////////") 
       print (" Cannot connect to " + servername + ".") 
       print (" //////////////////////////////////////////") 

os.system('cls' if os.name == 'nt' else 'clear') 
array = [] 
with open("C:/Users/myname/Desktop/PythonUpdate/serverlist.txt", "r") as f: 
    for servername in f: 


     copyfiles(servername.strip()) 

這個問題似乎喜歡它的實現呢?

+1

你的函數只處理複製到一個單一的網絡目的地,所以沒有什麼可轉移到如果'shutil'失敗。 – zwer

+0

對不起,我忘了發佈額外的代碼。我修好了它。 – Prox

+3

使用純粹的'except:'這樣的語句是一個糟糕的編程習慣,因爲它可以隱藏各種不相關的異常。更加詳細一些。 – martineau

回答

1

雖然您使用try-catch塊的想法是正確的,但您應該更確切地知道您認爲哪些條件是可原諒的。例如,如果您以某種方式得到MemoryErrorKeyboardInterrupt,則不想繼續。

作爲第一步,你應該只陷阱OSError,因爲這是shutil.copy用來表示各種讀/寫錯誤(至少 是什麼shutil.copyfile的文件說)。據this post,你的錯誤是最有可能成爲一個WindowsError(這是OSError一個子類):

try: 
    shutil.copy(files, destination) 
except WindowsError: 
    print('...') 

如果有可能是其他原因導致的異常,可以進一步縮小的確切原因使用else子句的擴展形式測試錯誤對象本身。例如,WindowsError有一個屬性winerror,其中包含異常的系統級錯誤代碼。您可能希望有可能的候選原諒:

你的代碼可能看起來是這樣的:

try: 
    shutil.copy(files, destination) 
except WindowsError as ex: 
    if ex.winerror in (53, 54, 55, 57, 59, 64, 70, 88): 
     print('...') 
    else: 
     raise 

您可能還需要檢查異常的filename2屬性。這會告訴你,你期望的文件是否導致了這個異常。此檢查不相關的一個關於winerror,可以連同或排除上面所示的一個來完成:

try: 
    shutil.copy(files, destination) 
except WindowsError as ex: 
    if ex.filename2.startswith('//' + filename2): 
     print('...') 
    else: 
     raise 
相關問題