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

View File

@ -17,12 +17,13 @@
# License for the specific language governing permissions and limitations
# under the License.
import contextlib
import os
import random
import re
import socket
import sys
import contextlib
import tempfile
import distutils.version
import netifaces
@ -161,6 +162,17 @@ def progress_bar(name, max_am, reverse=False):
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):
try:
__import__(module_name)