Skip to content

Instantly share code, notes, and snippets.

@japsu
Created February 28, 2012 09:01
Show Gist options
  • Save japsu/1931430 to your computer and use it in GitHub Desktop.
Save japsu/1931430 to your computer and use it in GitHub Desktop.
mkxtemp - a temporary file context manager for use by external processes that need temp files
#!/usr/bin/env python
# Mkxtemp - a temporary file context manager for use by external processes
# Placed in the Public Domain by Santtu Pajukanta <santtu@pajukanta.fi> 2012
from contextlib import contextmanager
from tempfile import NamedTemporaryFile
import os
import unittest
@contextmanager
def mkxtemp():
with NamedTemporaryFile(delete=False) as f:
name = f.name
try:
yield name
finally:
os.unlink(name)
class MkxtempTest(unittest.TestCase):
def test_mkxtemp(self):
with mkxtemp() as path:
# Has a non-empty filename.
self.assertTrue(len(path))
# The file exists.
self.assertTrue(os.path.exists(path))
# The file can be written.
with open(path, "wb") as f:
f.write("foo")
# The file can be read and reading it returns what was written.
with open(path, "rb") as f:
self.assertEquals(f.read(), "foo")
# The file still exists and can be accessed.
self.assertTrue(os.stat(path))
# The file no longer exists.
self.assertFalse(os.path.exists(path))
if __name__ == "__main__":
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment