# brightway2 / brightway2 / _config.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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 # -*- coding: utf-8 -* import os import json import tempfile class Config(object): """A singleton that store configuration settings. Default data directory is brightway in the user's home directory, and is stored as config.dir. Other configuration settings can also be assigned as needed. Args: *path* (str, optional): The path of the data directory. Must be writeable. """ def __init__(self, path=None): self.is_temp_dir = False self.reset(path) def check_dir(self, dir=None): """Check is directory is writeable.""" return os.access(dir or self.dir, os.W_OK) def reset(self, path=None): """Reset to original configuration. Useful for testing.""" # Use _dir instead of dir beacuse need to check dir ourselves self._dir = self.get_home_directory(path) if not self.check_dir(): self.dir = tempfile.mkdtemp() self.is_temp_dir = True print "Your changes will not be saved! Set a writeable directory!" print "Current data directory is:" print self.dir self.load_preferences() def load_preferences(self): """Load a set of preferences from a file in the home directory. Preferences as stored as config.p.""" try: self.p = json.load(open(os.path.join( self.dir, "preferences.json"))) except: self.p = {} def save_preferences(self): """Serialize preferences to disk.""" with open(os.path.join(self.dir, "preferences.json"), "w") as f: json.dump(self.p, f, indent=2) def get_home_directory(self, path=None): """Get data directory, trying in order: * Provided path (optional) * BRIGHTWAY2-DIR environment variable * brightway2 in user's home directory To set the environment variable: * Unix/Max: export BRIGHTWAY2-DIR=/path/to/brightway2/directory * Windows: set BRIGHTWAY2-DIR=\path\to\brightway2\directory """ if path: return path envvar = os.getenv("BRIGHTWAY2-DIR") if envvar: return envvar else: return os.path.expanduser("~/brightway2") def request_dir(self, dirname): """Return True if directory already exists or can be created.""" path = os.path.join(self.dir, dirname) if self.check_dir(path): return True else: try: os.mkdir(path) return True except: return False def _get_dir(self): return self._dir def _set_dir(self, d): self._dir = d if not self.check_dir(): raise OSError("This directory is not writeable") dir = property(_get_dir, _set_dir) config = Config()