Skip to content Skip to sidebar Skip to footer

How Do I Change Directory Back To My Original Working Directory With Python?

I have a function that resembles the one below. I'm not sure how to use the os module to get back to my original working directory at the conclusion of the jar's execution. def ru

Solution 1:

A context manager is a very appropriate tool for this job:

from contextlib import contextmanager

@contextmanagerdefcwd(path):
    oldpwd=os.getcwd()
    os.chdir(path)
    try:
        yieldfinally:
        os.chdir(oldpwd)

...used as:

os.chdir('/tmp') # for testing purposes, be in a known directoryprint'before context manager: %s' % os.getcwd()
with cwd('/'):
    # code inside this block, and only inside this block, is in the new directoryprint'inside context manager: %s' % os.getcwd()
print'after context manager: %s' % os.getcwd()

...which will yield something like:

before context manager:/tmpinside context manager:/after context manager:/tmp

This is actually superior to the cd - shell builtin, inasmuch as it also takes care of changing directories back when a block is exited due to an exception being thrown.


For your specific use case, this would instead be:

with cwd(testDir):
    os.system(cmd)

Another option to consider is using subprocess.call() instead of os.system(), which will let you specify a working directory for the command to run:

# note: better to modify this tonot need shell=Trueif possible
subprocess.call(cmd, cwd=testDir, shell=True)

...which would prevent you from needing to change the interpreter's directory at all.

Solution 2:

You simply need to add the line:

os.chdir(owd)

Just a note this was also answered in your other question.

Solution 3:

The advice to use os.chdir(owd) is good. It would be wise to put the code which needs the changed directory in a try:finally block (or in python 2.6 and later, a with: block.) That reduces the risk that you will accidentally put a return in the code before the change back to the original directory.

defrun(): 
    owd = os.getcwd()
    try:
        #first change dir to build_dir path
        os.chdir(testDir)
        #run jar from test directory
        os.system(cmd)
    finally:
        #change dir back to original working directory (owd)
        os.chdir(owd)

Solution 4:

A context-manager is overkill for this situation (executing a system command). The best solution is to use the subprocess module instead (Python 2.4 onwards) and the run or popen methods with the cwd argument.

So, your code can be replaced with:

defrun(): 
    #run jar from test directory
    subprocess.run(cmd, cwd=testDir)

See https://bugs.python.org/issue25625 and https://docs.python.org/3/library/subprocess.html#subprocess-replacements.

Solution 5:

Python is case sensitive so when typing the path make sure it's the same as the directory you want to set.

import osos.getcwd()

os.chdir('C:\\')

Post a Comment for "How Do I Change Directory Back To My Original Working Directory With Python?"