在问题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