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

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

项目:qtim_ROP    作者:QTIM-Lab    | 项目源码 | 文件源码
def initialize(unet=None, classifier=None):
    # Setup appdirs
    dirs = AppDirs("DeepROP", "QTIM", version=__version__)
    conf_dir = dirs.user_config_dir
    conf_file = join(conf_dir, 'config.yaml')

    if not isdir(conf_dir):
        makedirs(conf_dir)

    if not isfile(conf_file):
        config_dict = {'unet_directory': unet, 'classifier_directory': classifier}

        with open(conf_file, 'w') as f:
            yaml.dump(config_dict, f, default_flow_style=False)

    return yaml.load(open(conf_file, 'r')), conf_file
项目:cti-stix-validator    作者:oasis-open    | 项目源码 | 文件源码
def init_requests_cache(refresh_cache=False):
    """
    Initializes a cache which the ``requests`` library will consult for
    responses, before making network requests.

    :param refresh_cache: Whether the cache should be cleared out
    """
    # Cache data from external sources; used in some checks
    dirs = AppDirs("stix2-validator", "OASIS")
    # Create cache dir if doesn't exist
    try:
        os.makedirs(dirs.user_cache_dir)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise
    requests_cache.install_cache(
        cache_name=os.path.join(dirs.user_cache_dir, 'py{}cache'.format(
            sys.version_info[0])),
        expire_after=datetime.timedelta(weeks=1))

    if refresh_cache:
        clear_requests_cache()
项目:niceman    作者:ReproNim    | 项目源码 | 文件源码
def get_conda_test_dir():
    dirs = AppDirs('niceman')
    test_dir = os.path.join(dirs.user_cache_dir, 'conda_test')
    if os.path.exists(test_dir):
        return test_dir
    # Miniconda isn't installed, so install it
    if sys.platform.startswith('darwin'):
        miniconda_sh = "Miniconda2-latest-MacOSX-x86_64.sh"
    elif sys.platform.startswith('linux'):
        miniconda_sh = "Miniconda2-latest-Linux-x86_64.sh"
    else:
        raise ValueError("Conda test not supported with platform %s " %
                         sys.platform)
    call("mkdir -p " + test_dir + "; "
         "cd " + test_dir + "; "
         "curl -O https://repo.continuum.io/miniconda/" + miniconda_sh + "; "
         "bash -b " + miniconda_sh + " -b -p ./miniconda; "
         "./miniconda/bin/conda create -y -n mytest python=2.7; "
         "./miniconda/envs/mytest/bin/conda install -y xz -n mytest; "
         "./miniconda/envs/mytest/bin/pip install rpaths;",
         shell=True)
    return test_dir
项目:caller-lookup    作者:scottphilip    | 项目源码 | 文件源码
def _init_dirs(self, config_dir, data_dir, log_dir):
    d = AppDirs()
    self.config_dir = join(AppDirs().site_config_dir,
                           CallerLookupKeys.APP_NAME) if config_dir is None else config_dir
    self.data_dir = join(d.site_data_dir, CallerLookupKeys.APP_NAME) if data_dir is None else data_dir
    self.log_dir = join(d.user_log_dir, CallerLookupKeys.APP_NAME) if log_dir is None else log_dir
    __make_dir(self, self.config_dir)
    __make_dir(self, self.data_dir)
    __make_dir(self, self.log_dir)
项目:adblockradio    作者:quasoft    | 项目源码 | 文件源码
def get_data_dir():
    dirs = AppDirs("adblockradio", "quasoft")
    return dirs.user_data_dir
项目:OpenRAFAM    作者:jazzido    | 项目源码 | 文件源码
def appdir():
    """ Retorna el directorio donde deben estar los archivos de rafam_extract.
        Crea el directorio si no existe. """
    ad = appdirs.AppDirs(APP_NAME, APP_AUTHOR)
    config_dir = ad.user_config_dir

    if not os.path.isdir(config_dir):
        os.makedirs(config_dir)

    return config_dir
项目:Electrify    作者:jyapayne    | 项目源码 | 文件源码
def get_data_path(dir_path):
    parts = dir_path.split('/')
    dirs = AppDirs('Electrify', 'Electrify')
    data_path = path_join(dirs.user_data_dir, *parts)

    if is_windows():
        data_path = data_path.replace(u'\\', u'/')

    if not os.path.exists(data_path):
        os.makedirs(data_path)

    return data_path
项目:pyfilesystem2    作者:PyFilesystem    | 项目源码 | 文件源码
def __init__(self,
                 appname,
                 author=None,
                 version=None,
                 roaming=False,
                 create=True):
        self.app_dirs = AppDirs(appname, author, version, roaming)
        self.create = create
        super(_AppFS, self).__init__(
            getattr(self.app_dirs, self.app_dir),
            create=create
        )
项目:Weather-App    作者:Tomasz-Kluczkowski    | 项目源码 | 文件源码
def app_directories():
    """Generate dictionary with paths to the application folders."""
    user_dirs = appdirs.AppDirs("Weather_App", "")
    local_app_dir = user_dirs.user_data_dir
    data_dirs = {"Database": "", "Debug": ""}
    for sub_dir in data_dirs:
        path = os.path.join(local_app_dir, sub_dir)
        data_dirs[sub_dir] = path
    return data_dirs
项目:telegram-send    作者:rahiel    | 项目源码 | 文件源码
def get_config_path():
    return AppDirs("telegram-send").user_config_dir + ".conf"
项目:hangoutsbot    作者:das7pad    | 项目源码 | 文件源码
def main():
    """Main entry point"""
    # Build default paths for files.
    dirs = appdirs.AppDirs("hangupsbot", "hangupsbot")
    default_log_path = os.path.join(dirs.user_data_dir, "hangupsbot.log")
    default_cookies_path = os.path.join(dirs.user_data_dir, "cookies.json")
    default_config_path = os.path.join(dirs.user_data_dir, "config.json")
    default_memory_path = os.path.join(dirs.user_data_dir, "memory.json")

    # Configure argument parser
    parser = argparse.ArgumentParser(
        prog="hangupsbot",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("-d", "--debug", action="store_true",
                        help=_("log detailed debugging messages"))
    parser.add_argument("--log", default=default_log_path,
                        help=_("log file path"))
    parser.add_argument("--cookies", default=default_cookies_path,
                        help=_("cookie storage path"))
    parser.add_argument("--memory", default=default_memory_path,
                        help=_("memory storage path"))
    parser.add_argument("--config", default=default_config_path,
                        help=_("config storage path"))
    parser.add_argument("--retries", default=5, type=int,
                        help=_("Maximum disconnect / reconnect retries before "
                               "quitting"))
    parser.add_argument("--version", action="version",
                        version="%(prog)s {}".format(version.__version__),
                        help=_("show program\"s version number and exit"))
    args = parser.parse_args()


    # Create all necessary directories.
    for path in [args.log, args.cookies, args.config, args.memory]:
        directory = os.path.dirname(path)
        if directory and not os.path.isdir(directory):
            try:
                os.makedirs(directory)
            except OSError as err:
                sys.exit(_("Failed to create directory: %s"), err)

    # If there is no config file in user data directory, copy default one there
    if not os.path.isfile(args.config):
        try:
            shutil.copy(
                os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]),
                                             "config.json")),
                args.config)
        except (OSError, IOError) as err:
            sys.exit(_("Failed to copy default config file: %s"), err)

    configure_logging(args)

    # initialise the bot
    bot = HangupsBot(args.cookies, args.config, args.memory, args.retries)

    # start the bot
    bot.run()
项目:Mausoleum    作者:mandeep    | 项目源码 | 文件源码
def __init__(self, parent=None):
        """Initialize the config page's configuration group."""
        super(ConfigTomb, self).__init__(parent)

        config_directory = AppDirs('mausoleum', 'Mandeep').user_config_dir

        if not os.path.exists(config_directory):
            os.makedirs(config_directory)

        settings = pkg_resources.resource_filename(__name__, 'settings.toml')
        with open(settings) as default_config:
            default_config = default_config.read()

        self.user_config_file = os.path.join(config_directory, 'settings.toml')
        if not os.path.isfile(self.user_config_file):
            with open(self.user_config_file, 'a') as new_config_file:
                new_config_file.write(default_config)

        with open(self.user_config_file) as conffile:
            self.config = pytoml.load(conffile)

        config_box = QGroupBox("Configure Mausoleum")

        self.tomb_path_label = QLabel('Tomb Path', self)
        self.tomb_path_line = QLineEdit()
        self.tomb_path_line.setReadOnly(True)
        self.tomb_path_button = QPushButton('Select Path')

        self.tomb_path_button.clicked.connect(lambda: self.select_tomb_install_path(self.config))

        tomb_path_layout = QVBoxLayout()

        tomb_path_config_layout = QHBoxLayout()
        tomb_path_config_layout.addWidget(self.tomb_path_label)
        tomb_path_config_layout.addWidget(self.tomb_path_line)
        tomb_path_config_layout.addWidget(self.tomb_path_button)

        tomb_path_layout.addLayout(tomb_path_config_layout)

        config_box.setLayout(tomb_path_layout)

        main_layout = QVBoxLayout()
        main_layout.addWidget(config_box)
        main_layout.addStretch(1)
        self.setLayout(main_layout)

        self.set_tomb_path(self.config)
项目:Weather-App    作者:Tomasz-Kluczkowski    | 项目源码 | 文件源码
def __init__(self, controller):
        """Initialize Report class.

        Args:
            controller (Controller): controller object which will 
            store all the data required by each segment of the 
            application.

        :Attributes:
        :v_link (dict): Link to access variables in controller.
        :conn (sqlite3.Connection): Database object
        :cur (sqlite3.Cursor): Database cursor.
        :data_dirs (dict[str, str]): Data directories for the
            application.

        """
        self.controller = controller
        self.v_link = self.controller.app_data
        """:type : dict[str, any]"""

        # Create necessary application folders in 
        # C:\Users\User\AppData\Local
        user_dirs = appdirs.AppDirs("Weather_App", "")
        local_app_dir = user_dirs.user_data_dir
        self.data_dirs = {"Database": "",
                          "Debug": ""}
        for sub_dir in self.data_dirs:
            path = os.path.join(local_app_dir, sub_dir)
            self.data_dirs[sub_dir] = path
            os.makedirs(path, exist_ok=True)

        # Establish database connection.
        self.conn = sqlite3.connect(os.path.join(self.data_dirs["Database"],
                                                 "locations.db"))
        self.cur = self.conn.cursor()
        self.cur.execute("CREATE TABLE IF NOT EXISTS locations("
                         "Id INTEGER NOT NULL PRIMARY KEY , "
                         "Location TEXT NOT NULL UNIQUE, "
                         "Num_of_calls INTEGER NOT NULL DEFAULT 0, "
                         "Units TEXT)")
        # Read the last used units from the database and set in
        # controller.
        try:
            self.cur.execute("SELECT Units FROM locations WHERE Id=1")
            last_units = self.cur.fetchall()[0][0]
            if last_units != "":
                self.v_link["var_units"].set(last_units)
        # In case of the initial run with an empty database, default
        # units are metric.
        except IndexError:
            self.v_link["var_units"].set("metric")
        self.conn.commit()
        # Initial list of locations from previous use of the app for
        # loc_combobox ordered by amount of previous calls.
        self.combo_drop_menu()
项目:voodoo-pack    作者:NikkyAI    | 项目源码 | 文件源码
def __init__(self, config, debug, packs):
        self.debug = debug
        if self.debug:
            print('using encoding {}'.format(sys.stdout.encoding))
        self.config_path = Path(config).resolve()
        self.packs = packs

        self.cache_dir = appdirs.AppDirs(
            appname='voodoo', appauthor='nikky').user_cache_dir

        # parse config
        config_dir = self.config_path.parent
        self.global_config = {}

        config_suffix = self.config_path.suffix
        if config_suffix == '.yaml':
            config_dir.mkdir(parents=True, exist_ok=True)
            output = io.StringIO()

            default_config = pkg_resources.resource_string(__name__, 'data/default.yaml').decode()
            output.write(default_config)

            output.write('\n# END DEFAULTS\n\n# BEGIN CONFIG\n\n')
            with open(self.config_path) as infile:
                output.write(infile.read())
            self.config_str = output.getvalue()
            output.close()

            self.global_config = yaml.safe_load(self.config_str)
            if self.debug:
                print(yaml.dump(self.global_config))
            self.config_path = config_dir
            temp_path = self.global_config.get('temp_path')
            if temp_path:
                temp_path = Path(self.config_path, temp_path)
                temp_path.mkdir(parents=True, exist_ok=True)
                temp_path = Path(temp_path, 'generated_config.yaml')
                with open(temp_path, 'w') as outfile:
                    outfile.write(self.config_str)
        else:
            print('requires yaml config file')
            exit(-1)

        # auth_file = args.auth or config.get('authentication', None)
        # auth = config.get('authentication', {})
        # if args.username_github and args.password_github:
        #     auth_github = {'username': args.username, 'password': args.password}
        #     auth['github'] = auth_github