Skip to content

Instantly share code, notes, and snippets.

@wahello
Forked from Tatsh/pushd.py
Created January 26, 2021 02:15
Show Gist options
  • Save wahello/369d385653833b148c91d8309f9c70e6 to your computer and use it in GitHub Desktop.
Save wahello/369d385653833b148c91d8309f9c70e6 to your computer and use it in GitHub Desktop.
pushd for Python
from os import chdir, getcwd
from os.path import realpath
class PushdContext:
cwd = None
original_dir = None
def __init__(self, dirname):
self.cwd = realpath(dirname)
def __enter__(self):
self.original_dir = getcwd()
chdir(self.cwd)
return self
def __exit__(self, type, value, tb):
chdir(self.original_dir)
def pushd(dirname):
return PushdContext(dirname)
# Example use
with pushd('./anfplaylists') as ctx:
print(ctx.cwd, ctx.original_dir)
print(getcwd())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment