What you're doing already is the equivalent of cd -
.
The cd
shell builtin updates the OLDPWD
shell variable (notably "shell variable", not "environment variable", so the value isn't inherited by subprocesses), and that value is used for cd -
. However, there's no underlying operating system call equivalent to this; it's purely a shell function. As such, in a non-shell language, maintaining a similar variable is your own responsibility if you want to be able to revert.
One thing you might consider is a context manager:
from contextlib import contextmanager
@contextmanager
def cwd(path):
oldpwd=os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(oldpwd)
...used as:
os.chdir('/tmp') # for testing purposes, be in a known directory
print 'before context manager: %s' % os.getcwd()
with cwd('/'):
print 'inside context manager: %s' % os.getcwd()
print 'after context manager: %s' % os.getcwd()
...which will yield something like:
before context manager: /tmp
inside context manager: /
after context manager: /tmp
This is actually superior to the shell builtin for which you're requesting an equivalent: Unlike cd -
, this also takes care of changing back when a block is exited due to an exception being thrown, whereas an early function exit triggered by do_something || return
-style error handling in shell would provide no such guarantee. It also can be nested, and invocations won't overwrite each others OLDPWD
values -- as would happen if you had nested shell functions using cd -
.