Take the 2-minute tour ×

I know how to create a temporary directory in Python using tempfile.

I have though a class that encapsulates the user environment. I have also a Unit test which creates a temporary dummy user environment and populates it with some files that are used for testing. After this is done I want to clean everything up, thus removing everything from that dummy user directory (using shutils.rmtree)

I have a dummy class wrapping the original one that prevents it from getting the real user directory and returns the dummy instead. Though I'm afraid somebody might forget this and perhaps change it or completely remove the wrapper class. This might work and the developer will end up loosing everything from his/her home directory. Though this might teach him/her a good lesson, it is not acceptable.

I can check that '/tmp/' is at the path start of the user home, so that I know it's safe to delete, but that won't work with windows. As tempfile already knows how to create a directory it would be also able to tell if a directory is in the temporal area. Though I can't find out how to do it.

Any ideas?

share|improve this question
Why do you want to delete such a directory? Let the OS do this for you. –  user647772 Nov 5 '12 at 13:25
And /tmp/ is on the root for temp files in some Unixcies, it won't be for Windows and OSX and no doubt some others –  Mark Nov 5 '12 at 13:29
@Tichodroma: it won't. Per the Python docs, "The user of mkdtemp() is responsible for deleting the temporary directory and its contents when done with it." –  larsmans Nov 5 '12 at 13:30
@Tichodroma: AFAICT OS only cleans the temporal paths on startup, so when working on a server you might have months of unit test runs. Mix it with a CI and you'll end up with a lot of directories cluttering whatever you want to find in there... –  estani Nov 5 '12 at 13:31
@Mark: that's why I say it won't work (though I though OSX was not overriding this unix behavior, thanks for the heads up!) –  estani Nov 5 '12 at 13:32
add comment

1 Answer

up vote 2 down vote accepted

This is what tempfile.gettempdir() is for.

However, you may want rethink how you signal that the 'home directory' is a temporary test-only setup. You could add an extra file (.this-is-a-test-homedir or similar), use a clear 'temporary' username.

Or, better yet, remove the dummy wrapper altogether and have the test create the temporary user directory before running the test, then clean it up when tearing down the test.

share|improve this answer
How could I missed it! Thanks! I'm testing the wrapped class, so I can't remove the wrapper but that was exactly the function I was looking for. I think the help could do with a list of functions somewhere in the page... at least it would have help me... Thanks again –  estani Nov 5 '12 at 13:36
add comment

Your Answer


