tags:

views:

7092

answers:

7

"cd" as in the shell command to change working directory ...

+2  A: 

os.chdir is the Python cd

PEZ
+2  A: 

os.chdir() is the right way.

Federico Ramponi
+9  A: 

You can change the working directory with os.chdir( path ).

There are two best practices to follow:

  1. Catch the exception (WindowsError, OSError) on invalid path. If the exception is thrown, do not perform any recursive operations, especially destructive ones. They will operate on the old path and not the new one.
  2. Return to your old directory when you're done. This is done in an exception-safe manner by wrapping your chdir call in a class:
    class Chdir:         
      def __init__( self, newPath ):  
        self.savedPath = os.getcwd()
        os.chdir(newPath)

      def __del__( self ):
        os.chdir( self.savedPath )

Note that this snippet assumes that self.savedPath is still valid. Improving the handling of this is an exercise left up to the programmer.

Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use os.chdir() to change the CWD of the calling process.

sludge
I've heard somewhere that you can change the CWD of the parent process in Plan9. I don't remember in what context I heard it even, but anyway. =)
PEZ
Although you're on the right track with returning to your old dir, __del__ is the *wrong* way to do it. Python is a GC'd language and doesn't support RAII. Use a context manager and the with statement instead (__enter__ and __exit__).
Rhamphoryncus
+14  A: 

I would use os.chdir probably. It works like this:

os.chdir("/path/to/change/to")

By the way, if you need to figure out your current path, use os.getcwd().

More here: http://effbot.org/librarybook/os.htm

Evan Fosmark
+2  A: 

You probably already know this, but I'd like to remind people that if you change directory in a program, you won't be in that directory when the program exits and returns you to the shell.

Paul Tomblin
True on Windows, but not on Unix-based systems.
Brian Clapper
+2  A: 

If you're using a relatively new version of Python, you can also use a context manager, such as this one:

from __future__ import with_statement
from grizzled.os import working_directory

with working_directory(path_to_directory):
    # code in here occurs within the directory

# code here is in the original directory
Brian Clapper
A: 

and for easy interactive use, ipython has all the common shell commands built in.

Autoplectic