Make a tempdir context manager function

This commit is contained in:
Joshua Harlow 2012-03-18 22:26:01 -07:00
parent a2fc6a8c2d
commit bee1f55cbe
2 changed files with 14 additions and 6 deletions

View File

@ -19,7 +19,6 @@ import json
import os import os
import re import re
import tarfile import tarfile
import tempfile
import urllib2 import urllib2
import urlparse import urlparse
@ -219,16 +218,13 @@ class Image(object):
found_name = True found_name = True
break break
if not found_name: if not found_name:
tdir = tempfile.mkdtemp() with utils.tempdir() as tdir:
try:
fetch_fn = sh.joinpths(tdir, url_fn) fetch_fn = sh.joinpths(tdir, url_fn)
down.UrlLibDownloader(self.url, fetch_fn).download() down.UrlLibDownloader(self.url, fetch_fn).download()
locations = Unpacker().unpack(url_fn, fetch_fn, tdir) locations = Unpacker().unpack(url_fn, fetch_fn, tdir)
tgt_image_name = self._generate_img_name(url_fn) tgt_image_name = self._generate_img_name(url_fn)
self._register(tgt_image_name, locations) self._register(tgt_image_name, locations)
return tgt_image_name return tgt_image_name
finally:
sh.deldir(tdir)
else: else:
return None return None

View File

@ -17,12 +17,13 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import contextlib
import os import os
import random import random
import re import re
import socket import socket
import sys import sys
import contextlib import tempfile
import distutils.version import distutils.version
import netifaces import netifaces
@ -161,6 +162,17 @@ def progress_bar(name, max_am, reverse=False):
p_bar.finish() p_bar.finish()
@contextlib.contextmanager
def tempdir():
# This seems like it was only added in python 3.2
# Make it since its useful...
tdir = tempfile.mkdtemp()
try:
yield tdir
finally:
sh.deldir(tdir)
def import_module(module_name, quiet=True): def import_module(module_name, quiet=True):
try: try:
__import__(module_name) __import__(module_name)