pushd through os.system pushd through os.system python python

pushd through os.system


In Python 2.5 and later, I think a better method would be using a context manager, like so:

import contextlibimport os@contextlib.contextmanagerdef pushd(new_dir):    previous_dir = os.getcwd()    os.chdir(new_dir)    try:        yield    finally:        os.chdir(previous_dir)

You can then use it like the following:

with pushd('somewhere'):    print os.getcwd() # "somewhere"print os.getcwd() # "wherever you started"

By using a context manager you will be exception and return value safe: your code will always cd back to where it started from, even if you throw an exception or return from inside the context block.

You can also nest pushd calls in nested blocks, without having to rely on a global directory stack:

with pushd('somewhere'):    # do something    with pushd('another/place'):        # do something else    # do something back in "somewhere"


Each shell command runs in a separate process. It spawns a shell, executes the pushd command, and then the shell exits.

Just write the commands in the same shell script:

os.system("cd /directory/path/here; run the commands")

A nicer (perhaps) way is with the subprocess module:

from subprocess import PopenPopen("run the commands", shell=True, cwd="/directory/path/here")


I don't think you can call pushd from within an os.system() call:

>>> import os>>> ret = os.system("pushd /tmp")sh: pushd: not found

Maybe just maybe your system actually provides a pushd binary that triggers a shell internal function (I think I've seen this on FreeBSD beforeFreeBSD has some tricks like this, but not for pushd), but the current working directory of a process cannot be influenced by other processes -- so your first system() starts a shell, runs a hypothetical pushd, starts a shell, runs ls, starts a shell, runs a hypothetical popd... none of which influence each other.

You can use os.chdir("/home/path/") to change path: http://docs.python.org/library/os.html#os-file-dir