tags:

views:

1202

answers:

3

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 run(): 
    owd = os.getcwd()
    #first change dir to build_dir path
    os.chdir(testDir)
    #run jar from test directory
    os.system(cmd)
    #change dir back to original working directory (owd)

note: I think my code formatting is off - not sure why. My apologies in advance

+4  A: 

You simply need to add the line:

os.chdir(owd)

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

grieve
Noted. :) I Wanted to ensure my question was more specific and detailed in order to get the best help and also, post a code sample to add some more clarity to my question.
Amara
@Amara: That makes sense. :)
grieve
+2  A: 

os.chdir(owd) should do the trick (like you've done when changing to testDir)

+1  A: 

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.

def run(): 
    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)
fivebells