Skip to content

Instantly share code, notes, and snippets.

@chronossc
Created May 25, 2012 11:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chronossc/2787365 to your computer and use it in GitHub Desktop.
Save chronossc/2787365 to your computer and use it in GitHub Desktop.
A method to get first tmp dir in list and set it to environ so tempfile.mkstemp can use anywhere and you too at any place since it cache on os.environ.
def get_tmpdir(tmpdirs=tuple()):
# use a kind of cache
if not tmpdirs and os.environ.get('SET_TMPDIR_CHOICE',False):
return os.environ['SET_TMPDIR_CHOICE']
# starting here is a snipped copyed from /usr/lib/python2.7/tempfile.py
dirlist = []
# First, try the environment.
for envname in 'TMPDIR', 'TEMP', 'TMP':
dirname = os.getenv(envname)
if dirname: dirlist.append(dirname)
# Failing that, try OS-specific locations.
if os.name == 'riscos':
dirname = _os.getenv('Wimp$ScrapDir')
if dirname: dirlist.append(dirname)
elif os.name == 'nt':
dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
else:
dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
# As a last resort, the current directory.
try:
dirlist.append(os.getcwd())
except (AttributeError, _os.error):
dirlist.append(os.curdir)
# ending here the snipped copyed from /usr/lib/python2.7/tempfile.py
# set temp dir default list
default_tmp_dirs = (
os.path.join(os.environ.get('VIRTUAL_ENV'),sys.prefix), # venv/tmp, read http://www.python.org/dev/peps/pep-0405/
os.path.join(settings.PROJECT_ROOT_PATH,'tmp'), # project/tmp, project root path is defined on settings.py
) + tuple(dirlist)
for tmpdir in tmpdirs+default_tmp_dirs:
if not os.path.exists(tmpdir):
try:
os.makedirs(tmpdir)
except OSError:
continue # failed on create dir, no permission or existent file
if not os.path.isdir(tmpdir):
continue # is file
if not os.access(tmpdir,os.W_OK):
continue # not writeable
# set tmpdir environ variables
os.environ['TMPDIR'] = tmpdir
os.environ['TEMP'] = tmpdir
os.environ['TMP'] = tmpdir
# set a cache uniq var that we use as like cache key
os.environ['SET_TMPDIR_CHOICE'] = tmpdir
return tmpdir
raise OSError,u"Any temporary directory can be used, specify one."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment