Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change directory back to my original working directory with Python?

Tags:

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 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

like image 909
Amara Avatar asked Nov 18 '08 17:11

Amara


2 Answers

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

from contextlib import contextmanager  @contextmanager def cwd(path):     oldpwd=os.getcwd()     os.chdir(path)     try:         yield     finally:         os.chdir(oldpwd) 

...used as:

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

...which will yield something like:

before context manager: /tmp inside 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 to not need shell=True if possible subprocess.call(cmd, cwd=testDir, shell=True) 

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

like image 140
Charles Duffy Avatar answered Sep 20 '22 04:09

Charles Duffy


You simply need to add the line:

os.chdir(owd) 

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

like image 28
grieve Avatar answered Sep 22 '22 04:09

grieve