在我的程序中,我使用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())
這個問題似乎喜歡它的實現呢?
你的函數只處理複製到一個單一的網絡目的地,所以沒有什麼可轉移到如果'shutil'失敗。 – zwer
對不起,我忘了發佈額外的代碼。我修好了它。 – Prox
使用純粹的'except:'這樣的語句是一個糟糕的編程習慣,因爲它可以隱藏各種不相關的異常。更加詳細一些。 – martineau