-
Notifications
You must be signed in to change notification settings - Fork 222
/
os_helper.py
36 lines (27 loc) · 1010 Bytes
/
os_helper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import os
from pathlib import Path
from tempfile import gettempdir
__all__ = ['change_directory', 'make_tempdir']
class change_directory(object):
"""
Context manager for changing the current working directory.
Adapted from: ::
https://stackoverflow.com/questions/431684/how-do-i-cd-in-python/
"""
def __init__(self, newPath):
self.newPath = os.path.expanduser(newPath)
def __enter__(self):
self.savedPath = os.getcwd()
os.chdir(self.newPath)
def __exit__(self, etype, value, traceback):
os.chdir(self.savedPath)
def make_tempdir(prefix=None):
"""Create a temporary directory having a deterministic name. The directory
is created within the default OS temporary directory."""
if prefix is None:
name = 'devito-uid%s' % os.getuid()
else:
name = 'devito-%s-uid%s' % (str(prefix), os.getuid())
tmpdir = Path(gettempdir()).joinpath(name)
tmpdir.mkdir(parents=True, exist_ok=True)
return tmpdir