ChDir: a context manager for switching working directories
In your program you want to change the working directory temporarily, do some job there, then switch back to the original directory. Say you want to download some images to
/tmp. When done, you want to get back to the original location correctly, even if an exception was raised at the temp. location.
Let’s see the following example. We have a script, say at
/home/jabba/python/fetcher.py . We want to download some images to
/tmp, then work with them. After the download we want to create a subfolder “
process” in the same directory where the script
fetcher.py is located. We want to collect some extra info about the downloaded images and we want to store these pieces of information in the “
import os def download(li, folder): try: backup = os.getcwd() os.chdir(folder) for img in li: # download img somehow os.chdir(backup) except: # problem with download, handle it def main(): # step 1: download images to /tmp li = ["http://...1.jpg", "http://...2.jpg", "http://...3.jpg"] download(li, "/tmp") # step 2: create a "process" dir. HERE (where the script was launched) os.mkdir("process") # ...do some extra work...
There is a problem with the download method. If an image cannot be downloaded correctly and an exception occurs, we return from the method. However,
os.chdir(backup) is not executed and we remain in the
/tmp folder! In
main() in step 2 the
process directory will be created in
/tmp and not in the folder where we wanted it to be.
Well, you can always add a
finally block to the exception handler and place
os.chdir(backup) there, but it’s easy to forget. Is there an easier solution?
Yes, there is an easier solution. Use a context manager.
The previous example with a context manager:
import os def download(li, folder): with ChDir(folder): for img in li: # download img somehow def main(): # step 1: download images to /tmp li = ["http://...1.jpg", "http://...2.jpg", "http://...3.jpg"] download(li, "/tmp") # step 2: create a "process" dir. HERE (where the script was launched) os.mkdir("process") # ...do some extra work...
And now the source code of
import os class ChDir(object): """ Step into a directory temporarily. """ def __init__(self, path): self.old_dir = os.getcwd() self.new_dir = path def __enter__(self): os.chdir(self.new_dir) def __exit__(self, *args): os.chdir(self.old_dir)
ChDir is a context manager, you use it in a with block. At the beginning of the block you enter the given folder. When you leave the with block (even if you leave because of an exception), you are put back to the folder where you were before entering the with block.
Following this discussion thread @reddit, someone suggested using the PyFilesytem library. I think PyFilesytem is a very good solution but it may be too much for a short script. It’s like shooting a sparrow with a cannon :) For a simple script
ChDir is good enough for me. For a serious application, check out PyFilesytem.