本文介绍了如何编写一个可以还原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.

推荐答案

模块(如果在python脚本中处理路径,则应使用该模块)具有上下文管理器:

The path.py module (which you really should use if dealing with paths in python scripts) has a context manager:

subdir = d / 'subdir' #subdir is a path object, in the path.py module
with subdir:
  # here current dir is subdir

#not anymore

(信用证转到(来自Roberto Alsina)

(credits goes to this blog post from Roberto Alsina)

这篇关于如何编写一个可以还原cwd的装饰器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 11:35