def load_config(): resource_name = 'yt-bulk-py' if not bd.load_first_config(resource_name): sys.stderr.write('Creating config directory: ' + bd.save_config_path(resource_name)) conf_dir = bd.load_first_config(resource_name) conf_file = os.path.join(conf_dir, 'config') conf_skel = """# Configuration file for yt-bulk-py # Account information for the user doing the uploading. [user] email = [email protected] password = secret """ if not os.path.isfile(conf_file): with open(conf_file, 'w+b') as f: f.write(conf_skel) config = ConfigParser.ConfigParser() config.read(conf_file) if not 'user' in config.sections(): sys.stderr.write('Error: No [user] section in config file.') exit(1) if not 'email' in config.options('user') and 'password' in config.options('user'): sys.stderr.write('Error: Missing "email" or "password" options in config file.') exit(1) return (config.get('user', 'email'), config.get('user', 'password'))
def load_config(): resource_name = 'yt-bulk-py' if not bd.load_first_config(resource_name): sys.stderr.write('Creating config directory: ' + bd.save_config_path(resource_name)) conf_dir = bd.load_first_config(resource_name) conf_file = os.path.join(conf_dir, 'config') conf_skel = """# Configuration file for yt-bulk-py # Account information for the user doing the uploading. [user] email = [email protected] password = secret """ if not os.path.isfile(conf_file): with open(conf_file, 'w+b') as f: f.write(conf_skel) config = ConfigParser.ConfigParser() config.read(conf_file) if not 'user' in config.sections(): sys.stderr.write('Error: No [user] section in config file.') exit(1) if not 'email' in config.options('user') and 'password' in config.options( 'user'): sys.stderr.write( 'Error: Missing "email" or "password" options in config file.') exit(1) return (config.get('user', 'email'), config.get('user', 'password'))
def get_config(): config_path = BaseDirectory.load_first_config("pyfortunes.cfg") if not config_path: sys.exit("pyfortunes.cfg not found") config = configparser.ConfigParser() config.read(config_path) return config
def load(self, *, config_fd: TextIO = None) -> None: config = "" if config_fd: config = config_fd.read() else: # Local configurations (per project) are supposed to be static. # That's why it's only checked for 'loading' and never written to. # Essentially, all authentication-related changes, like # login/logout or macaroon-refresh, will not be persisted for the # next runs. file_path = "" if os.path.exists(LOCAL_CONFIG_FILENAME): file_path = LOCAL_CONFIG_FILENAME # FIXME: We don't know this for sure when loading the config. # Need a better separation of concerns. logger.warn( "Using local configuration ({!r}), changes will not be " "persisted.".format(file_path) ) else: file_path = BaseDirectory.load_first_config( "snapcraft", "snapcraft.cfg" ) if file_path and os.path.exists(file_path): with open(file_path, "r") as f: config = f.read() if config: _load_potentially_base64_config(self.parser, config)
def load_presets(self, force=False): qjackctl_conf = xdgbase.load_first_config('rncbc.org/QjackCtl.conf') if qjackctl_conf: mtime = os.path.getmtime(qjackctl_conf) changed = mtime > getattr(self, '_conf_mtime', 0) if changed: log.debug("QjackCtl configuration file mtime changed " "or previously unknown.") if force or changed or self.presets is None: log.debug("(Re-)Reading configuration.") ( preset_names, self.settings, self.default_preset ) = get_qjackctl_presets(qjackctl_conf, self.ignore_default) self.presets = {name: name.replace('_', ' ') for name in preset_names} self.create_menu() self._conf_mtime = mtime elif self.presets or self.presets is None: log.warning("QjackCtl configuration file not found.") if __debug__ and self.presets: log.debug("Removing stored presets from memory.") self.presets = {} self.settings = {} self.default_preset = None self.create_menu() return True # keep function scheduled
def load(self, *, config_fd: TextIO = None) -> None: config = '' if config_fd: config = config_fd.read() else: # Local configurations (per project) are supposed to be static. # That's why it's only checked for 'loading' and never written to. # Essentially, all authentication-related changes, like # login/logout or macaroon-refresh, will not be persisted for the # next runs. file_path = '' if os.path.exists(LOCAL_CONFIG_FILENAME): file_path = LOCAL_CONFIG_FILENAME # FIXME: We don't know this for sure when loading the config. # Need a better separation of concerns. logger.warn( 'Using local configuration ({!r}), changes will not be ' 'persisted.'.format(file_path)) else: file_path = BaseDirectory.load_first_config( 'snapcraft', 'snapcraft.cfg') if file_path and os.path.exists(file_path): with open(file_path, 'r') as f: config = f.read() if config: _load_potentially_base64_config(self.parser, config)
def read_convert_config(): config_path = "%s/%s" % (xdg.load_first_config('trip'), CONVERTER_CONFIG_FILE) config_dict = read_config(config_path) return config_dict
def write_ripper_config(): album_art_dict = { 'album_art_dir': "~/Pictures/album_art", 'embeded_art': True, 'folder_art': False } encoders_dict = {} encoders_dict[0] = {'codec': 'flac', 'output_dir': 'FLAC'} encoders_dict[1] = { 'codec': 'mp3', 'bitrate': 320, 'output_dir': 'MP3_320' } config_out = { 'album_art': album_art_dict, 'encoders': encoders_dict, 'output_prefix': "~/Music" } config_path = "%s/%s" % (xdg.load_first_config('trip'), RIPPER_CONFIG_FILE) write_config(config_out, config_path)
def getconfpath(resource): '''get conf path or create as required''' confpath = xdgbasedir.load_first_config(resource) if confpath is None: confpath = xdgbasedir.save_config_path(resource) # put filename on return confpath
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 hansei.exceptions.ConfigFileNotFoundError: If the requested configuration file cannot be found. """ path = BaseDirectory.load_first_config(xdg_config_dir, xdg_config_file) if path and os.path.isfile(path): return path raise exceptions.ConfigFileNotFoundError( 'Hansei is unable to find a configuration file. The following ' '(XDG compliant) paths have been searched: ' + ', '.join([ os.path.join(config_dir, xdg_config_dir, xdg_config_file) for config_dir in BaseDirectory.xdg_config_dirs ]))
def write_ripper_config(): album_art_dict = { 'album_art_dir': "~/Pictures/album_art", 'embeded_art': True, 'folder_art': False } encoders_dict = {} encoders_dict[0] = { 'codec': 'flac', 'output_dir': 'FLAC' } encoders_dict[1] = { 'codec': 'mp3', 'bitrate': 320, 'output_dir': 'MP3_320' } config_out = { 'album_art': album_art_dict, 'encoders': encoders_dict, 'output_prefix': "~/Music" } config_path = "%s/%s" % (xdg.load_first_config('trip'), RIPPER_CONFIG_FILE) write_config(config_out, config_path)
def __init__(self, sender=None, addresses=[], *args, **kwargs): super().__init__(*args, **kwargs) if not isinstance(addresses, list): addresses = [addresses] elif not addresses: import xdg.BaseDirectory as xdgb p = xdgb.load_first_config('notifier', 'addresses') if p is not None: with open(p, 'r') as f: addresses = f.read().split() if not addresses: raise ValueError('No email addresses (defaults are read from {}/addresses, one address per line)' .format(xdgb.save_config_path('notifier'))) for addr in addresses: if not isinstance(addr, str) or not '@' in addr: raise TypeError('`addresses` must be an email address or a list of email addresses') self._addresses = addresses if sender is None: sender = 'Notifier' self._sender = sender self._addr = 'notifier@{}'.format(platform.node())
def load_credentials(): p = xdgb.load_first_config('prisma', 'credentials') if p is None: exit('Please save your card number and password (each on its own line) in {}/credentials' .format(xdgb.save_config_path('prisma'))) with open(p, 'r') as f: t = f.read().split() return (t[0], t[1])
def _test(): from xdg import BaseDirectory as xdgbase qjackctl_conf = xdgbase.load_first_config('rncbc.org/QjackCtl.conf') if qjackctl_conf: presets, _, default = get_qjackctl_presets(qjackctl_conf, True) for preset in sorted(presets): print(preset, "*" if preset == default else '')
def parse_opts(): ''' This method parses the commandline options to next, if any, and it parses the configuration file ''' t = TUI() parser = OptionParser(usage=constants.USAGE) parser.add_option(u'-c', u'--conf', nargs=1, dest=u'new_path', help=u'NEW_PATH specifies a different configuration file') parser.add_option(u'-r', u'--random', action="store_const", dest="func", const=t.do_random, help=u'Start an ep for a random show') parser.add_option(u'-l', u'--list', action="store_const", dest="func", const=t.do_list, help=u'List all your shows') parser.add_option(u'-n', u'--new', action="store_const", dest="func", const=t.do_new, help=u'List shows for which there are new eps on your system') parser.add_option(u'-u', u'--update', action="store_const", dest="func", const=t.do_update, help=u'Connect to the TVRage database and update your show information') parser.add_option(u'-a', u'--add', action="store_const", dest="func", const=t.do_add_show, help=u'Add a show to the database') parser.add_option(u'--add_location', action="store_const", dest="func", const=t.do_add_show_location, help=u'Add a location for a show to the database') parser.add_option(u'--change', action="store_const", dest="func", const=t.do_change_show, help=u'Change the current season and ep for a show') parser.add_option(u'--scan', action="store_const", dest="func", const=t.do_scan, help=u'Scan your series path for shows') (options, args) = parser.parse_args() # Load a default config config = ConfigParser.SafeConfigParser() config.add_section(u'general') config.set(u'general', constants.ConfKeys.PLAYER_CMD, u'mplayer') config.set(u'general', constants.ConfKeys.SHOW_PATH, u'~/downloads/series') db_path = BaseDirectory.save_data_path('next') config.set(u'general', constants.ConfKeys.DB_PATH, db_path) # Load the config override if options.new_path: path = options.new_path if not (os.path.exists(path) and os.access(path, os.F_OK) and os.access(path, os.W_OK)): print u'No configfile found in "{0}", generating default configfile. Please modify, then start next again!'.format(path) gen_example(path) sys.exit(-1) else: path = BaseDirectory.load_first_config('next', 'next.conf') if path: config.read(path) result = dict(config.items(u'general')) for (k, v) in result.items(): # make sure bools are parsed correct if 'false' == v.lower() or 'no' == v.lower() or '0' == v: result[k] = False if 'true' == v.lower() or 'yes' == v.lower() or '1' == v: result[k] = True t.conf = result return options, result, args
def get_video_directories(self): """ Returns all the directories configured to scan for video content. :returns: list of the directories :rtype: list """ if 'video_dirs' in self._config: return self._config['video_dirs'] # TODO: Move this code into a common function to make it easier # to load up other directories. # Check for the ~/.config/user-dirs.dirs file user_dirs = BaseDirectory.load_first_config('user-dirs.dirs') if not user_dirs: # Attempt to generate out the default user-dirs.dirs config try: subprocess.call(['xdg-user-dirs-update']) except OSError: return [] # If the file still doesn't exist then something is very wrong # so just fail with an empty list. if not BaseDirectory.load_first_config('user-dirs.dirs'): return [] # Load the user-dirs.dirs config file to get the configured videos # directory. for line in open(BaseDirectory.load_first_config('user-dirs.dirs')): line = line.strip() if line.startswith('#'): continue (name, value) = line.split('=', 1) if name == 'XDG_VIDEOS_DIR': return [os.path.expandvars(value[1:-1])] return []
def load_config(self): try: filename = 'jenkins-indicator.yml' path = BaseDirectory.load_first_config(filename) or os.path.join(os.path.dirname(__file__), filename) logging.debug("loading config from: %s" % (path,)) with open(path) as f: self._config = yaml.load(f) return self._config except StandardError, e: import traceback traceback.print_exc() if hasattr(self, '_config'): return self._config raise
def load(self): # Local configurations (per project) are supposed to be static. # That's why it's only checked for 'loading' and never written to. # Essentially, all authentication-related changes, like login/logout # or macaroon-refresh, will not be persisted for the next runs. if os.path.exists(LOCAL_CONFIG_FILENAME): self.parser.read(LOCAL_CONFIG_FILENAME) logger.warn('Using local configuration (`{}`), changes will ' 'not be persisted.'.format(LOCAL_CONFIG_FILENAME)) return self.filename = BaseDirectory.load_first_config( 'snapcraft', 'snapcraft.cfg') if self.filename and os.path.exists(self.filename): self.parser.read(self.filename)
def test_load_first_config(self): tmpdir = tempfile.mkdtemp() tmpdir2 = tempfile.mkdtemp() tmpdir3 = tempfile.mkdtemp() path = os.path.join(tmpdir3, "wpokewefketnrhruit") os.mkdir(path) try: environ['XDG_CONFIG_HOME'] = tmpdir environ['XDG_CONFIG_DIRS'] = ":".join([tmpdir2, tmpdir3]) reload(BaseDirectory) configdir = BaseDirectory.load_first_config("wpokewefketnrhruit") self.assertEqual(configdir, path) finally: shutil.rmtree(tmpdir) shutil.rmtree(tmpdir2) shutil.rmtree(tmpdir3)
def get_config_value(filename: str, key: str) -> Optional[Any]: from swcc import SWCC_CONFIG_FILE, SWCC_CONFIG_PATH BaseDirectory.save_config_path(SWCC_CONFIG_PATH) config_dir: Optional[str] = BaseDirectory.load_first_config( SWCC_CONFIG_PATH) if config_dir: config_file = os.path.join(config_dir, SWCC_CONFIG_FILE) if os.path.exists(config_file): with open(config_file, 'r') as infile: config = toml.load(infile)['default'] return config.get(key) return None
def set_argparser_defaults_from_config(argparser): """Set defaults for the argument parser by reading the configuration file, if it exists. The configuration file should reside in the XDG data directory for this application (see :const:`APP_SHORTNAME`) and have the filename defined by :const:`CONFIG_FILENAME`. This is a standard INI file. All command line parameters can be set in the config file in the ``[options]`` section by taking the "long" parameter name and replacing all dashes with underscores (e. g. ``api_token = foobar``). Command line parameters without a value can be included in the config file by simply specifying the long parameter name without a value; e. g. adding a line containing just ``force`` will make the program behave as if the ``--force`` option was specified. :param argparser: Argument parser object to populate with defaults obtained from the configuration file. :type argparser: argparse.ArgumentParser :return: Nothing :rtype: None :raises configparser.Error: Config file has invalid syntax. :raises OSError: Config file exists, but cannot be opened (or read from). """ conf_dir = BaseDirectory.load_first_config(APP_SHORTNAME) if conf_dir is None: return path = os.path.join(conf_dir, CONFIG_FILENAME) if not os.path.isfile(path): return config = configparser.ConfigParser( allow_no_value=True, interpolation=None ) config.read_dict({"options": {}}) config.read(path) defaults = {} for key, value in config.items("options"): if value is None: # Specifying a parameter name without a value sets its value to True. value = True logging.debug("Setting default from config file: %s = %s", key, value) defaults[key] = value argparser.set_defaults(**defaults)
def __init__(self, screenlet_classobj, backend_type='caching', name='default'): object.__init__(self) # check type if not screenlet_classobj.__name__.endswith('Screenlet'): # TODO: also check for correct type (Screenlet-subclass)!! raise Exception( "ScreenletSession.__init__ has to be called with a valid Screenlet-classobject as first argument!" ) # init props self.name = name self.screenlet = screenlet_classobj self.instances = [] self.tempfile = TMP_DIR + '/' + TMP_FILE # check sys.args for "--session"-argument and override name, if set self.__parse_commandline() # set session path (and create dir-tree if not existent) p = screenlet_classobj.__name__[:-9] + '/' + self.name + '/' self.path = BaseDirectory.load_first_config('screenlets/' + p) if self.path == None: self.path = BaseDirectory.save_config_path('screenlets/' + p) if self.path == None: self.path = os.path.join(screenlets.DIR_CONFIG, p) if self.path: if backend_type == 'caching': self.backend = backend.CachingBackend(path=self.path) elif backend_type == 'gconf': self.backend = backend.GconfBackend() else: # no config-dir? use dummy-backend and note about problem self.backend = backend.ScreenletsBackend() print "Unable to init backend - settings will not be saved!" # WORKAROUND: connect to daemon (ideally the daemon should watch the # tmpfile for changes!!) # NOTE: daemon will be started by bus.get_object anyway!!! #check for daemon #proc = os.popen("""ps axo "%p,%a" | grep "python.*screenlets-daemon.py" | grep -v grep|cut -d',' -f1""").read() #procs = proc.split('\n') #if len(procs) <= 1: # os.system('python -u ' + screenlets.INSTALL_PREFIX + '/share/screenlets-manager/screenlets-daemon.py &') # print 'No Daemon, Launching Daemon' self.connect_daemon()
def update_config_value(filename: str, key: str, value: Any) -> None: from swcc import SWCC_CONFIG_PATH BaseDirectory.save_config_path(SWCC_CONFIG_PATH) config_dir = BaseDirectory.load_first_config(SWCC_CONFIG_PATH) config_file = os.path.join(config_dir, filename) if os.path.exists(config_file): with open(config_file, 'r') as infile: config = toml.load(infile) config['default'][key] = value else: config = {'default': {key: value}} with open(config_file, 'w') as outfile: toml.dump(config, outfile)
def genre_format(): genre_file = "%s/%s" % (xdg.load_first_config('trip'), 'genres') with open(genre_file) as config_file: genre_dictionary = {} index = 0 for a_line in config_file: genre = a_line.rstrip('\n') genre_dictionary[str(index)] = genre index += 1 return genre_dictionary
def get(): global config if config is None: try: config_dir_path = BaseDirectory.load_first_config("watson-jira") if config_dir_path == None: raise ConfigException("Failed to find config dir") path = os.path.join(config_dir_path, "config.yaml") stream = open(path) except Exception: raise ConfigException("Failed to open config file") try: config = yaml.safe_load(stream) except Exception: raise ConfigException("Failed to parse config file") return config
def __init__ (self, screenlet_classobj, backend_type='caching', name='default'): object.__init__(self) # check type if not screenlet_classobj.__name__.endswith('Screenlet'): # TODO: also check for correct type (Screenlet-subclass)!! raise Exception("ScreenletSession.__init__ has to be called with a valid Screenlet-classobject as first argument!") # init props self.name = name self.screenlet = screenlet_classobj self.instances = [] self.tempfile = TMP_DIR + '/' + TMP_FILE # check sys.args for "--session"-argument and override name, if set self.__parse_commandline() # set session path (and create dir-tree if not existent) p = screenlet_classobj.__name__[:-9] + '/' + self.name + '/' self.path = BaseDirectory.load_first_config('screenlets/' + p) if self.path == None: self.path = BaseDirectory.save_config_path('screenlets/' + p) if self.path == None: self.path = os.path.join(screenlets.DIR_CONFIG,p) if self.path: if backend_type == 'caching': self.backend = backend.CachingBackend(path=self.path) elif backend_type == 'gconf': self.backend = backend.GconfBackend() else: # no config-dir? use dummy-backend and note about problem self.backend = backend.ScreenletsBackend() print "Unable to init backend - settings will not be saved!" # WORKAROUND: connect to daemon (ideally the daemon should watch the # tmpfile for changes!!) # NOTE: daemon will be started by bus.get_object anyway!!! #check for daemon #proc = os.popen("""ps axo "%p,%a" | grep "python.*screenlets-daemon.py" | grep -v grep|cut -d',' -f1""").read() #procs = proc.split('\n') #if len(procs) <= 1: # os.system('python -u ' + screenlets.INSTALL_PREFIX + '/share/screenlets-manager/screenlets-daemon.py &') # print 'No Daemon, Launching Daemon' self.connect_daemon()
def __init__(self, app_name, cli_args=None, config_path=None): """ Add different config data sources in our order of priority. :param app_name: The name of the app. Used to configure file paths and config key prefixes. :param cli_args dict: A dict of arguments passed to the script :param config_path string: Path to a custom YAML config file to use. Default locations will be searched if not supplied. :return: """ self.app_name = app_name self._config = MergedConfig(app_name=self.app_name) # Add defaults from the dict above first self._config.add(DEFAULTS) # Values from the config file have the next highest level of priority if config_path: config_file = os.path.abspath(os.path.expanduser(config_path)) else: config_file = BaseDirectory.load_first_config( '%s.conf' % self.app_name.lower()) if config_file and os.path.exists(config_file): with open(config_file) as f: config_from_file = yaml.load(f) self._config.add(config_from_file) # Now environment variables. Only those prepended with the app name # will be included. self._config.add(os.environ, strip_app_name=True, filter_by_app_name=True) # CLI arguments have the highest level of priority if cli_args: self._config.add(cli_args, strip_app_name=True)
def main(): xdg_config = BaseDirectory.load_first_config("aiohex", "config.ini") p = argparse.ArgumentParser(description = 'Example aiohttp web app') p.add_argument("-c", "--config", help = 'Config path' , default = xdg_config , required = not xdg_config ) sub = p.add_subparsers(dest = 'command') sub.add_parser("serve", help = serve.__doc__) tp = sub.add_parser("transitions", help = transitions.__doc__) tp.add_argument("--session-id", type = uuid.UUID , help = "Show transitions for given session-id only" ) sub.add_parser("sessions", help = sessions.__doc__) args = p.parse_args(sys.argv[1:]) try: c = Config(args.config) except ConfigurationError as e: print(e) sys.exit(2) dispatch = dict( serve = serve , transitions = transitions , sessions = sessions ) sys.exit(dispatch[args.command]( args , asyncio.get_event_loop() , c , c.model ))
def load_config(main_section, interactive=False): config = ConfigParser({'log.level': "DEBUG", 'log.file': None}) path = None first_path = BaseDirectory.load_first_config('bugwarrior') if first_path is not None: path = os.path.join(first_path, 'bugwarriorrc') old_path = os.path.expanduser("~/.bugwarriorrc") if path is None or not os.path.exists(path): if os.path.exists(old_path): path = old_path else: path = os.path.join(BaseDirectory.save_config_path('bugwarrior'), 'bugwarriorrc') config.readfp(codecs.open( path, "r", "utf-8", )) config.interactive = interactive validate_config(config, main_section) return config
def load_config(main_section): config = ConfigParser({'log.level': "DEBUG", 'log.file': None}) path = None first_path = BaseDirectory.load_first_config('bugwarrior') if first_path is not None: path = os.path.join(first_path, 'bugwarriorrc') old_path = os.path.expanduser("~/.bugwarriorrc") if path is None or not os.path.exists(path): if os.path.exists(old_path): path = old_path else: path = os.path.join(BaseDirectory.save_config_path('bugwarrior'), 'bugwarriorrc') config.readfp( codecs.open( path, "r", "utf-8", ) ) config.interactive = False # TODO: make this a command-line option validate_config(config, main_section) return config
def get_ini(cls, prog: str, store=False): """ Select the best ini file for the program Args: prog: Name of the xdg section store: Is this file to write the options? Returns: The config file or None """ if store: d = BaseDirectory.save_config_path(prog) f = os.path.join(d, cls.Config) return open(f, 'wt') d = BaseDirectory.load_first_config(prog) if d is None: return None f = os.path.join(d, cls.Config) if os.path.isfile(f): return open(f, 'r') else: return None
BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' BULLET = '\u2022' config = configparser.ConfigParser() HOME = pathlib.Path.home() CONF_FOLDER = HOME / '.config' CONF_FILENAME = 'pypaper.conf' CONF_FILE = None if BaseDirectory is not None: CONF_FOLDER = pathlib.Path(BaseDirectory.xdg_config_home) CONF_FILE = pathlib.Path(BaseDirectory.load_first_config(CONF_FILENAME)) if CONF_FILE is None: CONF_FILE = CONF_FOLDER / CONF_FILENAME CONF_FILE.parent.mkdir(parents=True, exist_ok=True) DEFAULT = { 'General': { 'path': str(HOME / 'pypapers'), 'viewer': 'okular', 'title include': 0, }, 'ADS': { 'token': 'place your personal token here', 'max results': 20,
def read_ripper_config(): config_path = "%s/%s" % (xdg.load_first_config('trip'), RIPPER_CONFIG_FILE) config_dict = read_config(config_path) return config_dict
def get_config_file(filename, package=PACKAGE_NAME): """ Return path to @package/@filename if it exists anywhere in the config paths, else return None """ return base.load_first_config(package, filename)
def get_config_dir(): """Return the name of the directory containing the application's config file.""" config_dir = BaseDirectory.load_first_config("cligh") if config_dir is None: config_dir = BaseDirectory.save_config_path("cligh") return config_dir
def get_config_dir(): """Return the name of the directory containing the application's config file.""" config_dir = BaseDirectory.load_first_config('cligh') if config_dir is None: config_dir = BaseDirectory.save_config_path('cligh') return config_dir
def load(self): self.filename = BaseDirectory.load_first_config( 'snapcraft', 'snapcraft.cfg') if self.filename and os.path.exists(self.filename): self.parser.read(self.filename)
import json import os import os.path import configparser from xdg import BaseDirectory from pathlib import Path global_config = Path('/etc//xdg/noterc') _xdg_first_config = BaseDirectory.load_first_config('note') if _xdg_first_config: local_config = Path(_xdg_first_config) / 'noterc' else: local_config = Path(os.path.expanduser('~/.noterc')) _xdg_data = None # Just take the first one: '$HOME/.local/share/note' if list(BaseDirectory.load_data_paths('note')): _xdg_data = list(BaseDirectory.load_data_paths('note'))[0] if _xdg_data: DATA_PATH = Path(_xdg_data) else: DATA_PATH = Path(os.path.expanduser('~/.note')) # Initialize config parser object # Read global config first, overwrite with local config config = configparser.ConfigParser() config.read([str(global_config), str(local_config)])
import os from xdg import BaseDirectory from .config_manager import ConfigurationManager # Global configuration manager instance fc = BaseDirectory.load_first_config('angr-management') if fc is not None: config_path = os.path.join(fc, 'config') with open(config_path, 'r') as f: Conf = ConfigurationManager.parse(f) else: Conf = ConfigurationManager() APP_LOCATION = str( os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')) PLUGIN_PATH = str(os.path.join(APP_LOCATION, 'plugins')) RES_LOCATION = str(os.path.join(APP_LOCATION, 'resources')) IMG_LOCATION = str(os.path.join(RES_LOCATION, 'images')) FONT_LOCATION = str(os.path.join(RES_LOCATION, 'fonts'))
from xdg import BaseDirectory as base from xdg import DesktopEntry as desktop from configparser import ConfigParser POCO_DESKTOP = 'poco.desktop' POCO_PACKAGE = 'poco' DEFAULT_PREFIX_KEY = '<ctrl>q' DEFAULT_LIST_WORKSPACES = 'true' DEFAULT_POSITION = 'bottom' DEFAULT_WIDTH = '800' DEFAULT_AUTO_HINT = 'true' DEFAULT_AUTO_SELECT_FIRST_HINT = 'true' autostart_dir = base.save_config_path("autostart") autostart_file = os.path.join(autostart_dir, POCO_DESKTOP) config_dir = base.load_first_config(POCO_PACKAGE) if not config_dir: config_dir = base.save_config_path(POCO_PACKAGE) config_file_path = os.path.join(config_dir, "poco.cfg") parser = ConfigParser(interpolation=None) parser.read(config_file_path) need_write = False if not parser.has_section('interface'): parser.add_section('interface') need_write = True if not parser.has_option('interface', 'prefix_key'): parser.set('interface', 'prefix_key', DEFAULT_PREFIX_KEY) need_write = True if not parser.has_option('interface', 'list_workspaces'):