Python appdirs 模块,user_config_dir() 实例源码

我们从Python开源项目中,提取了以下17个代码示例,用于说明如何使用appdirs.user_config_dir()

项目:PlebNet    作者:rjwvandenberg    | 项目源码 | 文件源码
def tweet_arrival():
    options = UserOptions()
    options.read_settings()
    name = options.get('firstname') + ' ' + options.get('lastname')

    path = os.path.join(user_config_dir(), 'twitter.cfg')
    if not os.path.exists(path):
        print("Can't Tweet: {0} doesn't exist".format(path))
        return False
    cp = ConfigParser()
    cp.read(path)

    try:
        twitter = Twython(cp.get('twitter', 'app_key'),
                          cp.get('twitter', 'app_secret'),
                          cp.get('twitter', 'oauth_token'),
                          cp.get('twitter', 'oauth_token_secret'))
        twitter.update_status(
            status='Pleb %s has joined the botnet for good. #PlebNet #Cloudomate #Tribler #Bitcoin' % name)
        print("Tweeted arrival")
    except Exception, e:
        print e
        return False
    return True
项目:PlebNet    作者:rjwvandenberg    | 项目源码 | 文件源码
def generate_config():
    config = UserOptions()
    filename = os.path.join(user_config_dir(), 'cloudomate.cfg')
    if os.path.exists(filename):
        print("cloudomate.cfg already present at %s" % filename)
        config.read_settings(filename=filename)
        return config
    locale = random.choice(['cs_CZ', 'de_DE', 'dk_DK', 'es_ES', 'et_EE', 'hr_HR', 'it_IT'])
    fake = Factory().create(locale)
    cp = ConfigParser.ConfigParser()
    _generate_address(cp, fake)
    _generate_server(cp, fake)
    _generate_user(cp, fake)
    _remove_unicode(cp)
    with codecs.open(filename, 'w', 'utf8') as config_file:
        cp.write(config_file)
    return cp
项目:ChemDataExtractor    作者:mcs07    | 项目源码 | 文件源码
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)
项目:restfulpy    作者:Carrene    | 项目源码 | 文件源码
def configure(self, files=None, context=None, **kwargs):
        _context = {
            'process_name': self.process_name,
            'root_path': self.root_path,
            'data_dir': join(self.root_path, 'data'),
            'restfulpy_dir': abspath(dirname(__file__))
        }
        if context:
            _context.update(context)

        files = ([files] if isinstance(files, str) else files) or []
        local_config_file = join(user_config_dir(), '%s.yml' % self.name)
        if exists(local_config_file):  # pragma: no cover
            print('Gathering config file: %s' % local_config_file)
            files.insert(0, local_config_file)

        configure(config=self.builtin_configuration, files=files, context=_context, **kwargs)

    # noinspection PyMethodMayBeStatic
项目:lecli    作者:rapid7    | 项目源码 | 文件源码
def init_config():
    """
    Initialize config file in the OS specific config path if there is no config file exists.
    """
    config_dir = user_config_dir(lecli.__name__)

    if not os.path.exists(CONFIG_FILE_PATH):
        if not os.path.exists(config_dir):
            os.makedirs(config_dir)

        dummy_config = ConfigParser.ConfigParser()
        config_file = open(CONFIG_FILE_PATH, 'w')
        dummy_config.add_section(AUTH_SECTION)
        dummy_config.set(AUTH_SECTION, 'account_resource_id', '')
        dummy_config.set(AUTH_SECTION, 'owner_api_key_id', '')
        dummy_config.set(AUTH_SECTION, 'owner_api_key', '')
        dummy_config.set(AUTH_SECTION, 'rw_api_key', '')
        dummy_config.set(AUTH_SECTION, 'ro_api_key', '')

        dummy_config.add_section(CLI_FAVORITES_SECTION)
        dummy_config.add_section(URL_SECTION)
        dummy_config.set(URL_SECTION, 'api_url', 'https://rest.logentries.com')

        dummy_config.write(config_file)
        config_file.close()
        click.echo("An empty config file created in path %s, please check and configure it. To "
                   "learn how to get necessary api keys, go to this Logentries documentation "
                   "page: https://docs.logentries.com/docs/api-keys" % CONFIG_FILE_PATH)
    else:
        click.echo("Config file exists in the path: " + CONFIG_FILE_PATH, err=True)

    sys.exit(1)
项目:gitbot    作者:melkamar    | 项目源码 | 文件源码
def get_config_dir():
    return appdirs.user_config_dir("gitbot", "melkamar")
项目:PlebNet    作者:rjwvandenberg    | 项目源码 | 文件源码
def read_dictionary(self):
        config_dir = user_config_dir()
        filename = os.path.join(config_dir, 'DNA.json')

        if not os.path.exists(filename):
            self.dictionary = self.create_test_dict()
        else:
            with open(filename) as json_file:
                data = json.load(json_file)
                self.dictionary = data
        self.vps = self.dictionary['VPS']
项目:PlebNet    作者:rjwvandenberg    | 项目源码 | 文件源码
def write_dictionary(self):
        config_dir = user_config_dir()
        filename = os.path.join(config_dir, 'DNA.json')
        with open(filename, 'w') as json_file:
            json.dump(self.dictionary, json_file)
项目:PlebNet    作者:rjwvandenberg    | 项目源码 | 文件源码
def create_child_dna(self, provider, parentname, transaction_hash):
        dictionary = copy.deepcopy(self.dictionary)
        dictionary['Self'] = provider
        dictionary['parent'] = parentname
        dictionary['transaction_hash'] = transaction_hash
        #TODO
        #raise NotImlementedError('RESET ALL VARIABLES EXCEPT VPS')
        #TODO
        config_dir = user_config_dir()
        filename = os.path.join(config_dir, 'Child_DNA.json')
        with open(filename, 'w') as json_file:
            json.dump(dictionary, json_file)
项目:PlebNet    作者:rjwvandenberg    | 项目源码 | 文件源码
def save(self):
        config_dir = user_config_dir()
        filename = os.path.join(config_dir, CONFIG_NAME)
        with open(filename, 'w') as f:
            json.dump(self.config, f, indent=3)
项目:pymzn    作者:paolodragone    | 项目源码 | 文件源码
def _cfg_file():
    return os.path.join(appdirs.user_config_dir(__name__), 'config.yml')
项目:irida-miseq-uploader    作者:phac-nml    | 项目源码 | 文件源码
def __init__(self, show_new_ui=False, redirect=False, filename=None):
        wx.App.__init__(self, redirect, filename)
        self.get_app_info()
        self.check_for_update()

        user_config_file = path.join(user_config_dir("iridaUploader"), "config.conf")

        if not path.exists(user_config_file):
            dialog = SettingsDialog(first_run=True)
            dialog.ShowModal()

        self._show_main_app()
项目:AerisCloud    作者:AerisCloud    | 项目源码 | 文件源码
def config_dir():
    return user_config_dir(app_name, app_author)
项目:fdeunlock    作者:ypid    | 项目源码 | 文件源码
def __init__(self):
        super(FileVault, self).__init__()

        # File layout copied/reused from borgbackup.
        self._keys_dir = os.path.join(user_config_dir(appname='fdeunlock'), 'keys')

        os.makedirs(self._keys_dir, exist_ok=True)  # pylint: disable=unexpected-keyword-arg
        ensure_permissions(self._keys_dir, 0o0700)
项目:fdeunlock    作者:ypid    | 项目源码 | 文件源码
def get_user_dir(dir_type):
    dir_path = None
    if dir_type == 'config':
        dir_path = user_config_dir(appname='fdeunlock')
    elif dir_type == 'data':
        dir_path = user_data_dir(appname='fdeunlock')
    else:
        raise NotImplementedError
    os.makedirs(dir_path, exist_ok=True)  # pylint: disable=unexpected-keyword-arg
    return dir_path
项目:aw-core    作者:ActivityWatch    | 项目源码 | 文件源码
def get_config_dir(module_name: Optional[str]) -> str:
    config_dir = appdirs.user_config_dir("activitywatch")
    return os.path.join(config_dir, module_name) if module_name else config_dir
项目:CycloTrain    作者:spcmnspff99    | 项目源码 | 文件源码
def __init__(self):
        self.config = ConfigParser.SafeConfigParser()
        #look for a user specific config (presumably with api keys)    
        userConfigPath = appdirs.user_config_dir('CycloTrain')
        configFile = os.path.join(userConfigPath, 'config.ini') 
        if os.path.isfile(configFile):
                self.config.read(configFile)
        else:
            configFile = Utilities.getAppPrefix('config.ini')
            self.config.read(configFile)

        self.timezone = timezone(self.config.get('general', 'timezone')) 
        self.units = self.config.get("general", "units")
        self.apiKey = self.config.get("api_keys", "strava") if self.config.has_option('api_keys', 'strava') else None
        if self.config.has_option('general', 'logfile'):
            logfile = self.config.get("general", "logfile")
        else:
            logfile = Utilities.getAppPrefix('gb580.log')

        #logging http://www.tiawichiresearch.com/?p=31 / http://www.red-dove.com/python_logging.html
        handler = logging.FileHandler(logfile, mode='w')        
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(name)s %(lineno)d %(funcName)s %(message)s')
        handler.setFormatter(formatter)
        handler.setLevel(logging.DEBUG)

        self.logger = logging.getLogger('GB500')
        self.logger.addHandler(handler)
        self.logger.setLevel(logging.DEBUG)

        outputHandler = logging.StreamHandler()
        if self.config.getboolean("debug", "output"):
            level = logging.DEBUG
            format = '%(levelname)s %(funcName)s(%(lineno)d): %(message)s'
        else:
            level = logging.INFO
            format = '%(message)s'
        outputHandler.setFormatter(logging.Formatter(format))
        outputHandler.setLevel(level)
        self.logger.addHandler(outputHandler)

        #self._connectSerial()

        if self.__class__ is GB500:
            product = self.getProductModel()

            #downcasting to a specific model
            if product == "GB-580":
                self.__class__ = GB580