
On Tue, 14 Sept 2021 at 20:44, Marc-Andre Lemburg <mal@egenix.com> wrote:
I sometimes write Python scripts which need to work in specific work directories.
When putting such code into functions, the outer function typically does not expect the current work dir (CWD) to be changed, so wrap the code which need the (possibly) modified CWD using a simply context manager along the lines of:
class workdir: def __init__(self, dir): self.dir = dir def __enter__(self): self.curdir = os.getcwd() os.chdir(self.dir) def __exit__(self, *exc): os.chdir(self.curdir) return False
Would there be interest in adding something like this to the os module as os.workdir() ?
I've needed (and implemented my own version of) this often enough that I'd be in favour of it. Of course, as you show, it's not hard to write it yourself, so I can live with it not getting implemented, too :-) Paul