Skip to content

Instantly share code, notes, and snippets.

@Tatsh
Created October 24, 2013 05:26
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Tatsh/7131812 to your computer and use it in GitHub Desktop.
Save Tatsh/7131812 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())
@frans-fuerst
Copy link

Thanks, nice.
what is the function pushd for? Doesn't with PushdContext(PATH) do the same? And why do you implement cwd and originaldir as class members? Doesn't that conflict when you use that class in a nested way?

@teeks99
Copy link

teeks99 commented Jun 10, 2016

Awesome, this should be in the standard lib os module.

@aroonav
Copy link

aroonav commented Aug 5, 2016

Does anyone know why is pushd and popd not included in the python's standard os module yet?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment