在問題How do I "cd" in python中,接受的答案建議在類中包裝os.chdir調用,以便返回到原始目錄異常安全。這裏是推薦的代碼:如何在類中包裝不安全的python方法(例如os.chdir)使其線程/異常安全?
class Chdir:
def __init__(self, newPath):
self.savedPath = os.getcwd()
os.chdir(newPath)
def __del__(self):
os.chdir(self.savedPath)
有人可以詳細說明這是如何工作,使不安全的調用異常安全嗎?
感謝勞倫斯。非常徹底和清晰。 – zlovelady 2009-11-10 18:38:47
使用with語句更好(Python 2.5+) – compie 2011-08-17 15:05:18