[英]python 2.x:Conditionally Catching Exceptions (Ignore gracefully cleanup if the file is missing)
我有一個腳本可以在共享位置清理超過14天的日志。 現在,該腳本可以在不同主機上同時運行。 在特定情況下,如果兩個或更多主機嘗試清除同一文件,則只有一個主機將成功,而其他所有主機都將給出錯誤“無此文件或目錄”。 如果文件突然丟失,如何更新代碼以忽略正常清理。 以下是執行清理的部分代碼。 count
跟蹤刪除的文件數。
if os.stat(filename).st_mtime < current_time - 14 * 86400:
try:
os.remove(filename)
count += 1
except:
logger.warning("Not able to delete the file %s" % filename)
一種方法是在文件不存在的情況下“傳遞”異常,但在無法刪除文件的情況下繼續記錄警告。 如何包括此條件。
正如@Mark建議的那樣,您可以事先檢查文件是否存在,然后將其刪除,但是這種方法仍然存在潛在的競爭狀況。 它可以在os.stat
之后和os.remove
之前的腳本實例之間發生。 將所有引發錯誤的代碼移至try
/ except
,即可完成這項工作。 但是,據我了解,記錄真實消息存在問題。 附加標志attempted_delete
應該可以幫助您:
attempted_delete = False
try:
if os.stat(filename).st_mtime < current_time - 14 * 86400:
os.remove(filename)
count += 1
attempted_delete = True
except:
if attempted_delete:
logger.warning("Not able to delete the file %s" % filename)
一個沒有異常(類型)列表的except
子句是一個萬能的:易於設置但很難使用。 在這里,您應該專門捕獲(並忽略) FileNotFoundError
並記錄任何其他異常:
try:
if os.stat(filename).st_mtime < current_time - 14 * 86400:
os.remove(filename)
count += 1
except FileNotFoundError:
pass # file has already been deleted: all is fine
except:
logger.warning("Not able to delete the file %s" % filename)
上面是針對Python 3的,當您使用Python 2時,您只能檢查OSError然后控制其errno屬性:
try:
if os.stat(filename).st_mtime < current_time - 14 * 86400:
os.remove(filename)
count += 1
except OSError as e:
if e.errno != errno.ENOENT:
# do not log if file has already been deleted
logger.warning("Not able to delete the file %s" % filename)
except:
logger.warning("Not able to delete the file %s" % filename)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.