Equivalent of shell ‘cd’ command to change the working directory?

Posted on

Solving problem is about exposing yourself to as many situations as possible like Equivalent of shell ‘cd’ command to change the working directory? and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about Equivalent of shell ‘cd’ command to change the working directory?, which can be followed any time. Take easy to follow this discuss.

Equivalent of shell ‘cd’ command to change the working directory?

cd is the shell command to change the working directory.

How do I change the current working directory in Python?

Answer #1:

You can change the working directory with:

import os

There are two best practices to follow when using this method:

  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 can be done in an exception-safe manner by wrapping your chdir call in a context manager, like Brian M. Hunt did in his answer.

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.

Answered By: Michael Labbé

Answer #2:

Here’s an example of a context manager to change the working directory. It is simpler than an ActiveState version referred to elsewhere, but this gets the job done.

Context Manager: cd

import os
class cd:
    """Context manager for changing the current working directory"""
    def __init__(self, newPath):
        self.newPath = os.path.expanduser(newPath)
    def __enter__(self):
        self.savedPath = os.getcwd()
    def __exit__(self, etype, value, traceback):

Or try the more concise equivalent(below), using ContextManager.


import subprocess # just to call an arbitrary command e.g. 'ls'
# enter the directory like this:
with cd("~/Library"):
   # we are in ~/Library
# outside the context manager we are back wherever we started.
Answered By: Brian M. Hunt

Answer #3:

I would use os.chdir like this:


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

More here

Answered By: Evan Fosmark

Answer #4:

cd() is easy to write using a generator and a decorator.

from contextlib import contextmanager
import os
def cd(newdir):
    prevdir = os.getcwd()

Then, the directory is reverted even after an exception is thrown:

with cd('/tmp'):
    # ...
    raise Exception("There's no place like home.")
# Directory is now back to '/home'.
Answered By: cdunn2001

Answer #5:

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


If you prefer to roll your own:

import os
from contextlib import contextmanager
def working_directory(directory):
    owd = os.getcwd()
        yield directory
Answered By: Brian Clapper

Answer #6:

As already pointed out by others, all the solutions above only change the working directory of the current process. This is lost when you exit back to the Unix shell. If desperate you can change the parent shell directory on Unix with this horrible hack:

def quote_against_shell_expansion(s):
    import pipes
    return pipes.quote(s)
def put_text_back_into_terminal_input_buffer(text):
    # use of this means that it only works in an interactive session
    # (and if the user types while it runs they could insert characters between the characters in 'text'!)
    import fcntl, termios
    for c in text:
        fcntl.ioctl(1, termios.TIOCSTI, c)
def change_parent_process_directory(dest):
    # the horror
    put_text_back_into_terminal_input_buffer("cd "+quote_against_shell_expansion(dest)+"n")
Answered By: mrdiskodave

Answer #7:

os.chdir() is the right way.

Answer #8:

os.chdir() is the Pythonic version of cd.

Answered By: PEZ

Leave a Reply

Your email address will not be published. Required fields are marked *