def get_config_files(filename): """ Iterator to @filename in all config paths, with most important (takes precendence) files first """ return base.load_config_paths(PACKAGE_NAME, filename) or ()
def _get_config_file_path(xdg_config_dir, xdg_config_file): """Search ``XDG_CONFIG_DIRS`` for a config file and return the first found. Search each of the standard XDG configuration directories for a configuration file. Return as soon as a configuration file is found. Beware that by the time client code attempts to open the file, it may be gone or otherwise inaccessible. :param xdg_config_dir: A string. The name of the directory that is suffixed to the end of each of the ``XDG_CONFIG_DIRS`` paths. :param xdg_config_file: A string. The name of the configuration file that is being searched for. :returns: A ``str`` path to a configuration file. :raises nailgun.config.ConfigFileError: When no configuration file can be found. """ for config_dir in BaseDirectory.load_config_paths(xdg_config_dir): path = join(config_dir, xdg_config_file) if isfile(path): return path raise ConfigFileError( 'No configuration files could be located after searching for a file ' 'named "{0}" in the standard XDG configuration paths, such as ' '"~/.config/{1}/".'.format(xdg_config_file, xdg_config_dir) )
def _get_config_file_path(xdg_config_dir, xdg_config_file): """Search ``XDG_CONFIG_DIRS`` for a config file and return the first found. Search each of the standard XDG configuration directories for a configuration file. Return as soon as a configuration file is found. Beware that by the time client code attempts to open the file, it may be gone or otherwise inaccessible. :param xdg_config_dir: A string. The name of the directory that is suffixed to the end of each of the ``XDG_CONFIG_DIRS`` paths. :param xdg_config_file: A string. The name of the configuration file that is being searched for. :returns: A string. A path to a configuration file. :raises pulp_smash.config.base.ConfigFileNotFoundError: If the requested configuration file cannot be found. """ for config_dir in BaseDirectory.load_config_paths(xdg_config_dir): path = join(config_dir, xdg_config_file) if isfile(path): return path raise ConfigFileNotFoundError( 'No configuration files could be located after searching for a file ' 'named "{0}" in the standard XDG configuration paths, such as ' '"~/.config/{1}/".'.format(xdg_config_file, xdg_config_dir) )
def load_config(config_override): conf_path = None if config_override is None: for dir in BaseDirectory.load_config_paths('evdevremapkeys'): conf_path = Path(dir) / 'config.yaml' if conf_path.is_file(): break if conf_path is None: raise NameError('No config.yaml found') else: conf_path = Path(config_override) if not conf_path.is_file(): raise NameError('Cannot open %s' % config_override) with open(conf_path.as_posix(), 'r') as fd: config = yaml.safe_load(fd) for device in config['devices']: if 'remappings' in device: device['remappings'] = resolve_ecodes_remappings( device['remappings']) if 'commands' in device: device['commands'] = resolve_ecodes_commands( device['commands']) return config
def _get_config_file_path(xdg_config_dir, xdg_config_file): """Search ``XDG_CONFIG_DIRS`` for a config file and return the first found. Search each of the standard XDG configuration directories for a configuration file. Return as soon as a configuration file is found. Beware that by the time client code attempts to open the file, it may be gone or otherwise inaccessible. :param xdg_config_dir: A string. The name of the directory that is suffixed to the end of each of the ``XDG_CONFIG_DIRS`` paths. :param xdg_config_file: A string. The name of the configuration file that is being searched for. :returns: A ``str`` path to a configuration file. :raises nailgun.config.ConfigFileError: When no configuration file can be found. """ for config_dir in BaseDirectory.load_config_paths(xdg_config_dir): path = join(config_dir, xdg_config_file) if isfile(path): return path raise ConfigFileError( "No configuration files could be located after searching for a file " f'named "{xdg_config_file}" in the standard XDG configuration paths, such as ' f'"~/.config/{xdg_config_dir}/".' )
def _get_config_file_path(xdg_config_dir, xdg_config_file): """Search ``XDG_CONFIG_DIRS`` for a config file and return the first found. Search each of the standard XDG configuration directories for a configuration file. Return as soon as a configuration file is found. Beware that by the time client code attempts to open the file, it may be gone or otherwise inaccessible. :param xdg_config_dir: A string. The name of the directory that is suffixed to the end of each of the ``XDG_CONFIG_DIRS`` paths. :param xdg_config_file: A string. The name of the configuration file that is being searched for. :returns: A string. A path to a configuration file. :raises pulp_smash.exceptions.ConfigFileNotFoundError: If the requested configuration file cannot be found. """ paths = [ os.path.join(config_dir, xdg_config_file) for config_dir in BaseDirectory.load_config_paths(xdg_config_dir) ] for path in paths: if os.path.isfile(path): return path raise exceptions.ConfigFileNotFoundError( 'Pulp Smash is unable to find a configuration file. The following ' '(XDG compliant) paths have been searched: ' + ', '.join(paths))
def _get_config_file_path(xdg_config_dir, xdg_config_file): """Search ``XDG_CONFIG_DIRS`` for a config file and return the first found. Search each of the standard XDG configuration directories for a configuration file. Return as soon as a configuration file is found. Beware that by the time client code attempts to open the file, it may be gone or otherwise inaccessible. :param xdg_config_dir: A string. The name of the directory that is suffixed to the end of each of the ``XDG_CONFIG_DIRS`` paths. :param xdg_config_file: A string. The name of the configuration file that is being searched for. :returns: A string. A path to a configuration file. :raises pulp_smash.exceptions.ConfigFileNotFoundError: If the requested configuration file cannot be found. """ paths = [ os.path.join(config_dir, xdg_config_file) for config_dir in BaseDirectory.load_config_paths(xdg_config_dir) ] for path in paths: if os.path.isfile(path): return path raise exceptions.ConfigFileNotFoundError( 'Pulp Smash is unable to find a configuration file. The following ' '(XDG compliant) paths have been searched: ' + ', '.join(paths) )
def load_config(config_override): conf_path = None if config_override is None: for dir in BaseDirectory.load_config_paths('evdevremapkeys'): conf_path = Path(dir) / 'config.yaml' print(Path(dir)) if conf_path.is_file(): break if conf_path is None: raise NameError('No config.yaml found') else: conf_path = Path(config_override) if not conf_path.is_file(): raise NameError('Cannot open %s' % config_override) with open(conf_path.as_posix(), 'r') as fd: config = yaml.safe_load(fd) for device in config['devices']: device['remappings'] = normalize_config(device['remappings']) device['remappings'] = resolve_ecodes(device['remappings']) if 'modifier_groups' in device: for group in device['modifier_groups']: device['modifier_groups'][group] = \ normalize_config(device['modifier_groups'][group]) device['modifier_groups'][group] = \ resolve_ecodes(device['modifier_groups'][group]) return config
def get_load_path(cls, xdg_subdir=None, config_file=None): """Return the path to where a configuration file may be loaded from. Search each of the ``$XDG_CONFIG_DIRS`` for a file named ``$xdg_subdir/$config_file``. :param xdg_subdir: A string. The directory to append to each of the ``$XDG_CONFIG_DIRS``. Defaults to ``'pulp_smash'``. :param config_file: A string. The name of the settings file. Typically defaults to ``'settings.json'``. :returns: A string. The path to a configuration file, if one is found. :raises pulp_smash.exceptions.ConfigFileNotFoundError: If no configuration file is found. """ if xdg_subdir is None: xdg_subdir = cls._get_xdg_subdir() if config_file is None: config_file = cls._get_config_file() for dir_ in BaseDirectory.load_config_paths(xdg_subdir): path = os.path.join(dir_, config_file) if os.path.exists(path): return path raise exceptions.ConfigFileNotFoundError( "Pulp Smash is unable to find a configuration file. The " "following (XDG compliant) paths have been searched: " ", ".join((os.path.join(xdg_config_dir, xdg_subdir, config_file) for xdg_config_dir in BaseDirectory.xdg_config_dirs)))
def get_load_path(cls, xdg_subdir=None, config_file=None): """Return the path to where a configuration file may be loaded from. Search each of the ``$XDG_CONFIG_DIRS`` for a file named ``$xdg_subdir/$config_file``. :param xdg_subdir: A string. The directory to append to each of the ``$XDG_CONFIG_DIRS``. Defaults to ``'pulp_smash'``. :param config_file: A string. The name of the settings file. Typically defaults to ``'settings.json'``. :returns: A string. The path to a configuration file, if one is found. :raises pulp_smash.exceptions.ConfigFileNotFoundError: If no configuration file is found. """ if xdg_subdir is None: xdg_subdir = cls._get_xdg_subdir() if config_file is None: config_file = cls._get_config_file() for dir_ in BaseDirectory.load_config_paths(xdg_subdir): path = os.path.join(dir_, config_file) if os.path.exists(path): return path raise exceptions.ConfigFileNotFoundError( 'Pulp Smash is unable to find a configuration file. The ' 'following (XDG compliant) paths have been searched: ' ', '.join(( os.path.join(xdg_config_dir, xdg_subdir, config_file) for xdg_config_dir in BaseDirectory.xdg_config_dirs )) )
def read_config(name=None, update=None): """Read a ``becmd`` configuration file. :param name: File name to load the configuration from. When not given, try to load the configuration from the default locations. :type name: python:str :param update: Additional data with which to update the final configuration. :type update: python:dict :returns: A dictionary with parsed configuration statements. :rtype: python:dict """ log.debug("Enter: read_config(name={!r})".format(name)) # Try to find a configuration file. path = name if path is None: try: path = os.path.join( next(BaseDirectory.load_config_paths(PROG_NAME)), PROG_CONFIG_NAME) log.info("Found configuration file: '{}'.".format(path)) except StopIteration: log.info("No configuration file found.") # Load configuration file. data = {} if path: try: with open(path, 'r') as fp: data = toml.load(fp) except IOError: log.warning( "Could not read configuration file: '{}'.".format(path)) cfg = {k: v for k, v in data.items() if k in CONFIG_RESERVED_KEYS} cfg.update({ 'hosts': {k: v for k, v in data.items() if k not in CONFIG_RESERVED_KEYS}, }) if update is not None: mapping_update(cfg, update) # Validate configuration. try: cfg = validate(Config, cfg) except becmd.errors.ValidationError: log.error("Could not validate configuration file: '{}'.".format(path)) raise else: return cfg finally: log.debug("Exit: read_cfg(name={!r}) -> {!r}".format(name, cfg))
def _read(self): self._save = self._save_xdg for d in BaseDirectory.load_config_paths(CONFIG): path = os.path.join(d, DOMAINS) if os.path.exists(path): return self._read_file(path) else: return {}
def load(): for config_path in BaseDirectory.load_config_paths('buildhck', 'config.yaml'): with open(config_path) as f: obj = yaml.load(f) if obj: config.update(obj) if not path.isdir(build_directory()): makedirs(build_directory())
def load_config(app, filename): config.clear() for filename in BaseDirectory.load_config_paths('pb', filename): with open(filename) as f: obj = yaml.load(f) config.update(obj) if app: app.config.from_mapping(config) return config
def get_config_path(): try: tmp = next(BaseDirectory.load_config_paths(plugin_name_full)) except StopIteration: tmp = path.join(BaseDirectory.xdg_config_home, plugin_name_full) return path.join( tmp, config_filename )
def _read_configs_into(self, config, filepath='wordpressrc', config_name='config'): '''Used to read application config (blog name, etc.)''' for dir in BaseDirectory.load_config_paths(self.config_name): filename = os.path.join(dir, filepath) if not os.path.exists(filename): continue print "loading {0} from".format(config_name), filename with file(filename) as f: config.readfp(f) print 'config loaded'
def _get_config_paths(self): "Get configuration file paths" if _xdg_basedirectory: paths = list(reversed(list(_xdg_basedirectory.load_config_paths("")))) if not paths: # setup something for a useful log message paths.append(_xdg_basedirectory.save_config_path("")) else: self._log_xdg_import_error() paths = [_os_path.expanduser(_os_path.join("~", ".config"))] return [_os_path.join(path, "mutt-ldap.cfg") for path in paths]
def __init__(self, resource, legacy_path=None): self._dirty = False self._data = {} self._resource = resource for directory in xdg.load_config_paths(resource): self._load(os.path.join(directory, '%s.conf' % resource)) self._legacy_path = legacy_path if legacy_path is not None: self._load(legacy_path) self._dirty = True
def __init__(self): from mirage_linemode.util import ( ranger_name, plugin_name, plugin_name_full, plugin_filename, config_filename, theme_filename, plugin_path_in_pkg, config_path_in_pkg, theme_path_in_pkg, ) self._ranger_name = ranger_name self._plugin_name = plugin_name self._plugin_name_full = plugin_name_full self._plugin_filename = plugin_filename self._config_filename = config_filename self._theme_filename = theme_filename self._plugin_path_in_pkg = plugin_path_in_pkg self._config_path_in_pkg = config_path_in_pkg self._theme_path_in_pkg = theme_path_in_pkg try: path = next( BaseDirectory.load_config_paths(*(self._ranger_name, 'plugins'))) except StopIteration: path = os.path.join(BaseDirectory.xdg_config_home, *(self._ranger_name, 'plugins')) self._ranger_plugins_home = path try: path = next(BaseDirectory.load_config_paths( self._plugin_name_full)) except StopIteration: path = os.path.join(BaseDirectory.xdg_config_home, self._plugin_name_full) self._config_home = path script_path = os.path.dirname(__file__) self._plugin_path = os.path.join(script_path, self._plugin_path_in_pkg) self._config_path = os.path.join(script_path, self._config_path_in_pkg) self._theme_path = os.path.join(script_path, self._theme_path_in_pkg)
def load(): dct = {} for filepath in BaseDirectory.load_config_paths("mup/mup.yaml"): with open(filepath) as f: try: dct.update(yaml.load(f)) except Exception as exc: logging.exception("Failed to load {}, skipping it.".format(filepath)) return dct
def load(): dct = {} for filepath in BaseDirectory.load_config_paths("mup/mup.yaml"): with open(filepath) as f: try: dct.update(yaml.load(f)) except Exception as exc: logging.exception( "Failed to load {}, skipping it.".format(filepath)) return dct
def _get_config_paths(self): "Get configuration file paths" if _xdg_basedirectory: paths = list( reversed(list(_xdg_basedirectory.load_config_paths('')))) if not paths: # setup something for a useful log message paths.append(_xdg_basedirectory.save_config_path('')) else: self._log_xdg_import_error() paths = [_os_path.expanduser(_os_path.join('~', '.config'))] return [_os_path.join(path, 'mutt-ldap.cfg') for path in paths]
def _get_config_paths(self): "Get configuration file paths" if _xdg_basedirectory: paths = list(reversed(list( _xdg_basedirectory.load_config_paths('')))) if not paths: # setup something for a useful log message paths.append(_xdg_basedirectory.save_config_path('')) else: self._log_xdg_import_error() paths = [_os_path.expanduser(_os_path.join('~', '.mutt'))] # return [_os_path.join(path, 'mutt-ldap.cfg') for path in paths] return '/home/derek/.mutt/mutt-ldap.cfg'
def __init__(self): self._cparser = configparser.ConfigParser() paths = list(BaseDirectory.load_config_paths("mnemosyne")) paths.append(os.getcwd()) for path in paths: file = os.path.join(path, "mnemosyne.ini") if os.path.exists(file): self._cparser.read(file) self.consumer = Config.Consumer(self._cparser) self.web = Config.Web(self._cparser)
def test_load_config_paths(self): tmpdir = tempfile.mkdtemp() path = os.path.join(tmpdir, "wpokewefketnrhruit") os.mkdir(path) tmpdir2 = tempfile.mkdtemp() path2 = os.path.join(tmpdir2, "wpokewefketnrhruit") os.mkdir(path2) try: environ['XDG_CONFIG_HOME'] = tmpdir environ['XDG_CONFIG_DIRS'] = tmpdir2 + ":/etc/xdg" reload(BaseDirectory) configdirs = BaseDirectory.load_config_paths("wpokewefketnrhruit") self.assertEqual(list(configdirs), [path, path2]) finally: shutil.rmtree(tmpdir) shutil.rmtree(tmpdir2)
def config() -> Dict[str, Dict[str, str]]: """Returns the moodlecli configuration. """ config = configparser.ConfigParser() dict = {} # type: Dict[str, Dict[str, str]] for path in BaseDirectory.load_config_paths('moodlecli'): config.read(os.path.join(path, 'moodlecli.ini')) for section in config: for key in config[section]: if section not in dict: dict[section] = {} dict[section][key] = config[section][key] return dict
def search_configs(self, configfile, section, key, default=None): '''Looks through all configs named configfile for (section, key)''' for dir in BaseDirectory.load_config_paths(self.config_name): filename = os.path.join(dir, configfile) if not os.path.exists(filename): continue config = ConfigParser.SafeConfigParser() with file(filename) as f: config.readfp(f) if not config.has_section(section): continue if not config.has_option(section, key): continue return config.get(section, key) return default
def load_config(config_override): conf_path = None if config_override is None: for dir in BaseDirectory.load_config_paths('evdevremapkeys'): conf_path = Path(dir) / 'config.yaml' if conf_path.is_file(): break if conf_path is None: raise NameError('No config.yaml found') else: conf_path = Path(config_override) if not conf_path.is_file(): raise NameError('Cannot open %s' % config_override) with open(conf_path.as_posix(), 'r') as fd: config = yaml.safe_load(fd) return parse_config(config)
def autostart(environments): # get the autostart directories autodirs = BaseDirectory.load_config_paths("autostart") # find all the autostart files files = [] for mdir in autodirs: for path in glob.glob(os.path.join(mdir, "*.desktop")): try: autofile = AutostartFile(path) except ParsingError: print("Invalid .desktop file: " + path) else: if not autofile in files: files.append(autofile) # run them for autofile in files: autofile.run(environments)
def get_app_config(): # pragma: nocover """ Gets a dict with the global configuration files set in the XDG dirs. """ # NOTE: This is very quick and dirty and should be baked into the # configuration ecosystem of piper at a later point. ret = {} files = [f for f in BaseDirectory.load_config_paths('piper', 'piper.yml')] files.reverse() for conf in files: with open(conf) as f: data = yaml.safe_load(f.read()) ret.update(data) return ret
def __init__(self): gobject.GObject.__init__(self) self.config = Config.Config(tgcm.country_support) # Determine the path for XDG autostart dirs self.autofile_name = 'tgcm-%s.desktop' % tgcm.country_support self.user_autodir = None for foo in BaseDirectory.load_config_paths('autostart'): if foo.startswith(os.path.expanduser('~')): self.user_autodir = foo else: self.system_autodir = foo self.__create_desktop_entry_if_necessary() # Listen to file changes myfile = gio.File(self.user_autofile) self.desktopentry_monitor = myfile.monitor_file() self.desktopentry_monitor.connect('changed', self.on_desktopentry_changed)
def _get_configs_path(): """Get a list of possible configuration files, from the following sources: 1. All files that exists in constants.CONFS_PATH. 2. All XDG standard config files for "lago.conf", in reversed order of importance. Returns: list(str): list of files """ paths = [] xdg_paths = [ path for path in base_dirs.load_config_paths('lago', 'lago.conf') ] paths.extend([path for path in CONFS_PATH if os.path.exists(path)]) paths.extend(reversed(xdg_paths)) return paths
def mk_dynamic_account(self, payee, exclude, amount): if self.lgr is None: return self.unknownaccount or 'Expenses:Misc' else: from xdg import BaseDirectory import importlib for ledgerautosync_hooks in BaseDirectory.load_config_paths("ledgerautosync/hooks.py"): import sys sys.path.append(os.path.dirname(ledgerautosync_hooks)) mod = importlib.import_module( os.path.splitext(os.path.basename(ledgerautosync_hooks))[0] ) if hasattr(mod, "mk_dynamic_account"): res = mod.mk_dynamic_account(payee, exclude, amount) if res is not None: return res account = self.lgr.get_account_by_payee(payee, exclude) if account is None: return self.unknownaccount or 'Expenses:Misc' else: return account
def _load_raw_config(config_file=None): """Load ADAM config from default locations or ``config_file`` Locates and loads the configuration information for ADAM. If ``config_file`` is not None, loads it and returns the de-serialized YAML. If ``config_file`` is None, follows the XDG Base Directory specification to locate a file named ``$.../adam/config``, usually ``~/.config/adam/config``. Parameters ---------- config_file : str Path to config file to load, or None to search default locations. Returns ------- dict De-serialized configuration in the form of nested dictionaries. """ if config_file is None: # see if location is overridden via the environment config_file = os.environ.get("ADAM_CONFIG", None) if config_file is None: # get the default location (if exists) config_dir = next(xdgb.load_config_paths("adam"), None) if config_dir is not None: def_config_file = os.path.join(config_dir, ADAM_CONFIG_FN) if os.path.exists(def_config_file): config_file = def_config_file if config_file is None: return "", {} # Load the config file (if we have it) with open(config_file) as fp: return config_file, yaml.safe_load(fp)
def _get_config_file_location(): """ Locate a Braubuddy config file in the locations defined by the XDG spec. If no config file exists, deploy the default Braubuddy config file to the XDG config dir in the user's home dir ('~/.config/braubuddy/'). :returns: Path to config file. :rtype: :class:`unicode` """ for config_path in BaseDirectory.load_config_paths('braubuddy'): config_file_path = os.path.join( config_path, CONFIG_FILENAME_BRAUBUDDY) if os.path.isfile(config_file_path): break else: # No config file found. So deploy default config file to XDG config # dir in user home dir. config_path = os.path.join( BaseDirectory.xdg_config_home, 'braubuddy') config_file_path = _deploy_config_file(config_path) print 'Loading config from {0}'.format(config_file_path) return config_file_path
def get_config_file(self, filename): """Look for the proper config file path based on https://github.com/omkarkhatavkar/jirasync/issues/5 """ # Try to find the file from path exported to JIRASYNC_SETTINGS_PATH # this variable can be a directory path like /foo/bar # and also can be full path like /etc/foo/config.yaml path = os.environ.get("JIRASYNC_SETTINGS_PATH") if path is not None: if not path.endswith(("yaml", "yml")): path = os.path.join(path, filename) if os.path.exists(path): echo_success("Found config file in {}".format(path)) return path else: echo_error( "JIRASYNC_SETTINGS_PATH={0} cannot be found".format(path)) # Try to find in the XDG paths # look ~/.config/jirasync/config.yaml # then /etc/xdg/jirasync/config.yaml # then /etc/jirasync/config.yaml BaseDirectory.xdg_config_dirs.append("/etc") for dir_ in BaseDirectory.load_config_paths("jirasync"): path = os.path.join(dir_, filename) if os.path.exists(path): echo_success("Found config file in {}".format(path)) return path # load from current directory path = os.path.join(os.curdir, filename) if os.path.exists(path): echo_success("Found config file in {}".format(path)) return path raise IOError("{0} cannot be found".format(path))
def load_config(config_override): conf_path = None if config_override is None: for dir in BaseDirectory.load_config_paths('evdevremapkeys'): conf_path = Path(dir) / 'config.yaml' if conf_path.is_file(): break if conf_path is None: raise NameError('No config.yaml found') else: conf_path = Path(config_override) if not conf_path.is_file(): raise NameError('Cannot open %s' % config_override) with open(conf_path.as_posix(), 'r') as fd: config = yaml.safe_load(fd) for device in config['devices']: device['multiscan_affecting'] = normalize_config( device['multiscan_affecting']) device['multiscan_affecting'] = resolve_ecodes( device['multiscan_affecting']) multiscan_affecting_tmp = {} for multiscan_key, affected_dict in device[ 'multiscan_affecting'].items(): affected_ary = [] for aff_key in affected_dict: affected_ary.append(aff_key['code']) multiscan_affecting_tmp[multiscan_key[0]] = affected_ary device['multiscan_affecting'] = multiscan_affecting_tmp device['multiscan_delayed_keys'] = list( map(lambda c: ecodes.ecodes[c], device['multiscan_delayed_keys'])) device['remappings'] = normalize_config(device['remappings']) device['remappings'] = resolve_ecodes(device['remappings']) return config
def get_config(self, cli): config = ConfigParser.SafeConfigParser() config.add_section('general') config.set('general', 'couch_url', 'http://localhost:5984/tuyau') config.set('general', 'instance_name', '') read_config = False filepath = 'tuyau.rc' for dir in BaseDirectory.load_config_paths('tuyau'): filename = os.path.join(dir, filepath) if not os.path.exists(filename): continue with file(filename) as f: read_config = True config.readfp(f) path = os.path.join(BaseDirectory.save_config_path('tuyau'), 'tuyau.rc') if not read_config: self.write_empty_config(config, path) if not config.get('general', 'instance_name'): print("Config missing! Edit {} and fill in couch_url\n" "and instance_name".format(path)) return read_config and config
def load_yaml(app, filename): for filename in BaseDirectory.load_config_paths('pb', filename): with open(filename) as f: obj = yaml.load(f) app.config.from_mapping(obj)
mutex_groups = argument_parser.add_mutually_exclusive_group() mutex_groups.add_argument('-a', '--autostart', action='store_true') mutex_groups.add_argument('-f', '--desktop-file') argument_parser.add_argument('args', nargs=OPTIONAL, default=[]) def launch_desktop_file(desktop_file, *args): launcher = Gio.DesktopAppInfo.new_from_filename(desktop_file) launcher.launch_uris(args) __all__ = {'argument_parser', 'launch_desktop_file'} if __name__ == '__main__': from glob import glob from os import path from gi.repository import Gio from xdg import BaseDirectory args = argument_parser.parse_args() if args.autostart: for directory in BaseDirectory.load_config_paths('autostart'): for dentry in glob(path.join(directory, '*.desktop')): launch_desktop_file(dentry) elif args.desktop_file: launch_desktop_file(args.desktop_file, *args.args) else: exit(argument_parser.print_help())
from xdg import BaseDirectory import configparser import os import sys from pprint import pprint # Configuring the config filename _appname = (__package__ or 'planer.daemon').split('.')[0] _config_file = _appname + '.conf' _defaults_file = os.path.join(os.path.dirname(__file__), _config_file) # Read default and user configurations config = configparser.ConfigParser() with open(_defaults_file) as f: config.read_file(f, "defaults") config.read(os.path.join(path, _config_file) for path in BaseDirectory.load_config_paths(_appname)) # Database is absolute or relative to the xdg data home. _database_file = config['daemon']['database file'] _database_file = os.path.expanduser(_database_file) if not os.path.isabs(_database_file): config['daemon']['database file'] = os.path.join( BaseDirectory.save_data_path(_appname), config['daemon']['database file'])