如何编写一个恢复 cwd 的装饰器?
如何编写一个装饰器,将当前工作目录恢复到调用装饰函数之前的状态? 换句话说,如果我在执行 os.chdir() 的函数上使用装饰器,则调用函数后 cwd 将不会更改。
How do I write a decorator that restores the current working directory to what it was before the decorated function was called? In other words, if I use the decorator on a function that does an os.chdir()
, the cwd will not be changed after the function is called.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
装饰器的答案已经给出了; 它按照要求在函数定义阶段工作。
使用 Python 2.5+,您还可以选择使用上下文管理器在函数调用阶段执行此操作:
如果需要,可以在函数调用时使用它,因为:
这是一个不错的选择。
编辑:我按照 codeape 的建议添加了错误处理。 由于我的答案已被投票通过,因此可以公平地提供完整的答案,抛开所有其他问题。
The answer for a decorator has been given; it works at the function definition stage as requested.
With Python 2.5+, you also have an option to do that at the function call stage using a context manager:
which can be used if needed at the function call time as:
It's a nice option to have.
EDIT: I added error handling as suggested by codeape. Since my answer has been voted up, it's fair to offer a complete answer, all other issues aside.
path.py 模块(如果处理 python 脚本中的路径,你确实应该使用它)有一个上下文管理器:(
感谢 Roberto Alsina 的这篇博文)
The path.py module (which you really should use if dealing with paths in python scripts) has a context manager:
(credits goes to this blog post from Roberto Alsina)
给出的答案没有考虑到包装函数可能会引发异常。 在这种情况下,该目录将永远不会被恢复。 下面的代码在前面的答案中添加了异常处理。
作为装饰器:
以及作为上下文管理器:
The given answers fail to take into account that the wrapped function may raise an exception. In that case, the directory will never be restored. The code below adds exception handling to the previous answers.
as a decorator:
and as a context manager:
你不需要为你写它。 在 python 3.11 中,开发人员已经为您编写了它。 在 github.com 上查看代码。
You dont need to write it for you. With python 3.11, the developers have written it for you. Check out their code at github.com.
它的使用方法如下:
Here's how it's used: