2

I am writing a script that should change directory based on the input and then go back to the directory where the script was executed.

I am currently doing this:

old_dir = os.getcwd()
os.chdir(<new_dir>)
#do something
os.chdir(old_dir)
#do something

Is there a Python equivalent of cd - which would change the directory to the previous directory?

The following question expects an answer using any module while what I am looking for is something similar to cd -.

Community
  • 1
  • 1
gaganso
  • 2,914
  • 2
  • 26
  • 43

1 Answers1

6

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 -.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • Wow! learnt a lot! thank you. I read the following questions before posting this - http://stackoverflow.com/questions/14462833/is-it-possible-to-specify-the-previous-directory-python and http://stackoverflow.com/questions/299446/how-do-i-change-directory-back-to-my-original-working-directory-with-python. But none of the answers are as good as yours. Is there a way to link them to this answer? – gaganso Jun 23 '16 at 15:57
  • Hmm. I think the answer is also applicable to the latter -- in fact, I might copy it over there and close this question as duplicative of it, or the inverse. For the former it's merely related; a comment with a link might be appropriate. – Charles Duffy Jun 23 '16 at 15:59
  • Sure, Please do what seems right. – gaganso Jun 23 '16 at 16:00
  • 1
    ...actually, just realized these questions are tagged `python`, whereas my gold-badge dupe-closing powers are limited to `bash`, `shell`, and maybe these days `unix`, so we'll have some other folks weighing in on what seems the appropriate resolution rather than having it be a unilateral decision anyhow. :) – Charles Duffy Jun 23 '16 at 16:03