How to use the appdirs.user_config_dir function in appdirs

To help you get started, we’ve selected a few appdirs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github expectocode / telegram-export / telegram_export / __main__.py View on Github external
def load_config(filename):
    """Load config from the specified file and return the parsed config"""
    # Get a path to the file. If it was specified, it should be fine.
    # If it was not specified, assume it's config.ini in the script's dir.
    config_dir = appdirs.user_config_dir("telegram-export")

    if not filename:
        filename = os.path.join(config_dir, 'config.ini')

    if not os.path.isfile(filename):
        logger.warning("No config file! Make one in {} and find an example "
                       "config at https://github.com/expectocode/"
                       "telegram-export/blob/master/config.ini.example."
                       "Alternatively, use --config-file FILE".format(filename))
        exit(1)

    defaults = {
        'SessionName': 'exporter',
        'OutputDirectory': '.',
        'MediaWhitelist': 'chatphoto, photo, sticker',
        'MaxSize': '1MB',
github spartan-array / spartan / spartan / array / distarray.py View on Github external
tile.from_shape(ex.shape, dtype, tile_type=tile_type),
                  hint=worker_scores[i % len(worker_scores)][0])
  elif FLAGS.tile_assignment_strategy == 'serpentine':
    for ex, i in extents.iteritems():
      j = i % ctx.num_workers
      if (i / ctx.num_workers) % 2 == 1:
        j = (ctx.num_workers - 1 - j)

      tiles[ex] = ctx.create(
                    tile.from_shape(ex.shape, dtype, tile_type=tile_type),
                    hint=j)
  elif FLAGS.tile_assignment_strategy == 'static':
    all_extents = list(extents.iterkeys())
    all_extents.sort()
    if hasattr(appdirs, 'user_config_dir'):  # user_config_dir new to v1.3.0
      map_file = appdirs.user_config_dir('spartan') + '/tiles_map'
    else:
      map_file = appdirs.user_data_dir('spartan') + '/tiles_map'
    with open(map_file) as fp:
      for ex in all_extents:
        worker = int(fp.readline().strip())
        tiles[ex] = ctx.create(
                    tile.from_shape(ex.shape, dtype, tile_type=tile_type),
                    hint=worker)
  else: #  random
    for ex in extents:
      tiles[ex] = ctx.create(tile.from_shape(ex.shape, dtype, tile_type=tile_type))

  for ex in extents:
    tiles[ex] = tiles[ex].wait().tile_id

  #for ex, i in extents.iteritems():
github matthewearl / photo-a-day-aligner / pada.py View on Github external
if cli_args.debug:
        logging.getLogger().setLevel(logging.DEBUG)
    else:
        logging.getLogger().setLevel(logging.INFO)

    # Build up a list of potential config files to parse.
    config_paths = []
    try:
        import appdirs
    except ImportError:
        logging.warn("appdirs not installed, not reading site/user config")
    else:
        config_paths.append(
            os.path.join(
                appdirs.user_config_dir(APP_NAME, APP_AUTHOR),
                CONFIG_FILE_NAME))
        config_paths.append(
            os.path.join(
                appdirs.site_config_dir(APP_NAME, APP_AUTHOR),
                CONFIG_FILE_NAME))
    if cli_args.config:
        config_paths.append(cli_args.config)

    if cli_args.cmd == "print_config_paths":
        for config_path in config_paths:
            print config_path
        sys.exit(0)

    # Attempt to open each config file, and update the `cfg` dict with each
    # one.
    cfg = {}
github rapid7 / lecli / lecli / api_utils.py View on Github external
import hmac
import os
import json

import datetime

import click
import validators
from appdirs import user_config_dir

import lecli

AUTH_SECTION = 'Auth'
URL_SECTION = 'Url'
CONFIG = ConfigParser.ConfigParser()
CONFIG_FILE_PATH = os.path.join(user_config_dir(lecli.__name__), 'config.ini')
DEFAULT_API_URL = 'https://rest.logentries.com'


def print_config_error_and_exit(section=None, config_key=None, value=None):
    """
    Print appropriate apiutils error message and exit.
    """
    if not section:
        click.echo("Error: Configuration file '%s' not found" % CONFIG_FILE_PATH, err=True)
    elif not config_key:
        click.echo("Error: Section '%s' was not found in configuration file(%s)" %
                   (section, CONFIG_FILE_PATH), err=True)
    elif not value:
        click.echo("Error: Configuration key for %s was not found in configuration file(%s) in "
                   "'%s' section" % (config_key, CONFIG_FILE_PATH, section), err=True)
    else:
github CounterpartyXCP / counterparty-cli / counterpartycli / setup.py View on Github external
def extract_old_config():
    old_config = {}

    old_appdir = appdirs.user_config_dir(appauthor='Counterparty', appname='counterpartyd', roaming=True)
    old_configfile = os.path.join(old_appdir, 'counterpartyd.conf')

    if os.path.exists(old_configfile):
        configfile = configparser.SafeConfigParser(allow_no_value=True, inline_comment_prefixes=('#', ';'))
        configfile.read(old_configfile)
        if 'Default' in configfile:
            for key in configfile['Default']:
                new_key = key.replace('backend-rpc-', 'backend-')
                new_key = new_key.replace('blockchain-service-name', 'backend-name')
                new_value = configfile['Default'][key].replace('jmcorgan', 'addrindex')
                old_config[new_key] = new_value

    return old_config
github python-mario / mario / src / mario / config.py View on Github external
def get_config_dir():
    str_path = DEFAULTS["dir_path"] or appdirs.user_config_dir(utils.NAME)
    return pathlib.Path(str_path)
github XanaduAI / pennylane / pennylane / configuration.py View on Github external
def __init__(self, name):
        # Look for an existing configuration file
        self._config = {}
        self._filepath = None
        self._name = name
        self._user_config_dir = user_config_dir("pennylane", "Xanadu")
        self._env_config_dir = os.environ.get("PENNYLANE_CONF", "")

        # search the current directory the directory under environment
        # variable PENNYLANE_CONF, and default user config directory, in that order.
        directories = [os.curdir, self._env_config_dir, self._user_config_dir, ""]
        for idx, directory in enumerate(directories):
            try:
                self._filepath = os.path.join(directory, self._name)
                self.load(self._filepath)
                break
            except FileNotFoundError:
                if idx == len(directories) - 1:
                    log.info("No PennyLane configuration file found.")
github and3rson / clay / clay / settings.py View on Github external
def _ensure_directories(self):
        """
        Create config dir, config file & cache dir if they do not exist yet.
        """
        self._config_dir = appdirs.user_config_dir('clay', 'Clay')
        self._config_file_path = os.path.join(self._config_dir, 'config.yaml')
        self._colours_file_path = os.path.join(self._config_dir, 'colours.yaml')

        try:
            os.makedirs(self._config_dir)
        except OSError as error:
            if error.errno != errno.EEXIST:
                raise

        self._cache_dir = appdirs.user_cache_dir('clay', 'Clay')
        try:
            os.makedirs(self._cache_dir)
        except OSError as error:
            if error.errno != errno.EEXIST:
                raise
github mcs07 / ChemDataExtractor / chemdataextractor / config.py View on Github external
def __init__(self, path=None):
        """

        :param string path: (Optional) Path to config file location.
        """
        self._path = path
        self._data = {}

        # Use CHEMDATAEXTRACTOR_CONFIG environment variable if set
        if not self._path:
            self._path = os.environ.get('CHEMDATAEXTRACTOR_CONFIG')
        # Use OS-dependent config directory given by appdirs
        if not self._path:
            self._path = os.path.join(appdirs.user_config_dir('ChemDataExtractor'), 'chemdataextractor.yml')
        if os.path.isfile(self.path):
            with io.open(self.path, encoding='utf8') as f:
                self._data = yaml.safe_load(f)

appdirs

A small Python module for determining appropriate platform-specific dirs, e.g. a "user data dir".

MIT
Latest version published 4 years ago

Package Health Score

77 / 100
Full package analysis

Similar packages