Hello all,

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() ?

Example:

def backup_home_dir(account):
    with os.workdir(os.path.join('/home', account)):
        # Create a backup of the account dir, rooted at the account's
        # home dir
        restic.backup(repo, '.')

Notes:
- The context manager is not thread safe. There's no thread safe model
  for the current work dir. OTOH, scripts usually don't use threads,
  so not a big deal.
- The context manager could be made more elaborate, e.g. adding optional
  logging for debugging purposes.
- The same could be added to pathlib's objects as .workdir() method
  returning a context manager.

Thoughts ?

Thanks,
-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Experts (#1, Sep 14 2021)
>>> Python Projects, Coaching and Support ...    https://www.egenix.com/
>>> Python Product Development ...        https://consulting.egenix.com/
________________________________________________________________________

::: We implement business ideas - efficiently in both time and costs :::

   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
    D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
           Registered at Amtsgericht Duesseldorf: HRB 46611
               https://www.egenix.com/company/contact/
                     https://www.malemburg.com/

_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/C525UVPP3ALGTXDNFL2GFDV23KCHP3RL/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to