当前位置: 首页>>代码示例>>Python>>正文


Python appdirs.AppDirs方法代码示例

本文整理汇总了Python中appdirs.AppDirs方法的典型用法代码示例。如果您正苦于以下问题:Python appdirs.AppDirs方法的具体用法?Python appdirs.AppDirs怎么用?Python appdirs.AppDirs使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在appdirs的用法示例。


在下文中一共展示了appdirs.AppDirs方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: import appdirs [as 别名]
# 或者: from appdirs import AppDirs [as 别名]
def __init__(self, name=None, default_params={}):
        """name is going to be the generic name of the config folder

        e.g., /home/user/.config/<name>/<name>.cfg

        """
        if name is None:
            raise Exception("Name parameter must be provided")
        else:
            # use input parameters
            self.name = name
            self._default_params = copy.deepcopy(default_params)
            self.params = copy.deepcopy(default_params)

            # useful tool to handle XDG config file, path and parameters
            self.appdirs = appdirs.AppDirs(self.name)

            # useful tool to handle the config ini file
            self.config_parser = DynamicConfigParser()

            # Now, create the missing directories if needed
            self.init() # and read the user config file updating params if needed 
开发者ID:cokelaer,项目名称:bioservices,代码行数:24,代码来源:settings.py

示例2: __init__

# 需要导入模块: import appdirs [as 别名]
# 或者: from appdirs import AppDirs [as 别名]
def __init__(self):
        # set up the test account credentials
        Main.APP_NAME = "gphotos-sync-test"
        app_dirs = AppDirs(Main.APP_NAME)
        self.test_folder = Path(__file__).absolute().parent / "test_credentials"
        user_data = Path(app_dirs.user_data_dir)
        if not user_data.exists():
            user_data.mkdir(parents=True)
        user_config = Path(app_dirs.user_config_dir)
        if not user_config.exists():
            user_config.mkdir(parents=True)

        secret_file = self.test_folder / "client_secret.json"
        shutil.copy(secret_file, app_dirs.user_config_dir)

        self.gp = GooglePhotosSyncMain()
        self.parsed_args = None
        self.db_file = None
        self.root = None 
开发者ID:gilesknap,项目名称:gphotos-sync,代码行数:21,代码来源:test_setup.py

示例3: load_config_for_test

# 需要导入模块: import appdirs [as 别名]
# 或者: from appdirs import AppDirs [as 别名]
def load_config_for_test(cls):
        """Load the argparse configuration needed for the unittest"""
        if not cls.configuration:
            parser = getParser()
            for group in cls.groups.keys():
                for fnct in cls.groups[group]:
                    if (
                            fnct.must_be_loaded_by_unittest or
                            group in ('plugins',)
                    ):
                        fnct(parser)

            ad = AppDirs('AnyBlok')
            # load the global configuration file
            cls.parse_configfile(
                join(ad.site_config_dir, 'conf.cfg'), False)
            # load the user configuration file
            cls.parse_configfile(
                join(ad.user_config_dir, 'conf.cfg'), False)
            configfile = cls.get('configfile')
            if configfile:
                cls.parse_configfile(configfile, True) 
开发者ID:AnyBlok,项目名称:AnyBlok,代码行数:24,代码来源:config.py

示例4: init_requests_cache

# 需要导入模块: import appdirs [as 别名]
# 或者: from appdirs import AppDirs [as 别名]
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() 
开发者ID:oasis-open,项目名称:cti-stix-validator,代码行数:24,代码来源:util.py

示例5: _get_parser

# 需要导入模块: import appdirs [as 别名]
# 或者: from appdirs import AppDirs [as 别名]
def _get_parser(extra_args):
    """Return ArgumentParser with any extra arguments."""
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    dirs = appdirs.AppDirs('hangups', 'hangups')
    default_token_path = os.path.join(dirs.user_cache_dir, 'refresh_token.txt')
    parser.add_argument(
        '--token-path', default=default_token_path,
        help='path used to store OAuth refresh token'
    )
    parser.add_argument(
        '-d', '--debug', action='store_true',
        help='log detailed debugging messages'
    )
    for extra_arg in extra_args:
        parser.add_argument(extra_arg, required=True)
    return parser 
开发者ID:tdryer,项目名称:hangups,代码行数:20,代码来源:common.py

示例6: parse_options

# 需要导入模块: import appdirs [as 别名]
# 或者: from appdirs import AppDirs [as 别名]
def parse_options(cls, arguments):
        """Parse options

        :param arguments:
        """
        if arguments._get_args():
            raise ConfigurationException(
                'Positional arguments are forbidden')

        ad = AppDirs('AnyBlok')
        # load the global configuration file
        cls.parse_configfile(
            join(ad.site_config_dir, 'conf.cfg'), False)
        # load the user configuration file
        cls.parse_configfile(
            join(ad.user_config_dir, 'conf.cfg'), False)
        if 'configfile' in dict(arguments._get_kwargs()).keys():
            if arguments.configfile:
                cls.parse_configfile(arguments.configfile, True)

        for opt, value in arguments._get_kwargs():
            if opt not in cls.configuration or value:
                cls.set(opt, value)

        if 'logging_level' in cls.configuration:
            cls.initialize_logging() 
开发者ID:AnyBlok,项目名称:AnyBlok,代码行数:28,代码来源:config.py

示例7: create_profanity_filter

# 需要导入模块: import appdirs [as 别名]
# 或者: from appdirs import AppDirs [as 别名]
def create_profanity_filter() -> ProfanityFilter:
    app_dirs = AppDirs(APP_NAME)
    config_path = pathlib.Path(app_dirs.user_config_dir) / 'web-config.yaml'
    with suppress(FileExistsError):
        DEFAULT_CONFIG.to_yaml(config_path, exist_ok=False)
    return ProfanityFilter.from_yaml(config_path) 
开发者ID:rominf,项目名称:profanity-filter,代码行数:8,代码来源:web.py

示例8: get_config_path

# 需要导入模块: import appdirs [as 别名]
# 或者: from appdirs import AppDirs [as 别名]
def get_config_path():
    return AppDirs("telegram-send").user_config_dir + ".conf" 
开发者ID:rahiel,项目名称:telegram-send,代码行数:4,代码来源:telegram_send.py

示例9: _init_dirs

# 需要导入模块: import appdirs [as 别名]
# 或者: from appdirs import AppDirs [as 别名]
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) 
开发者ID:scottphilip,项目名称:caller-lookup,代码行数:11,代码来源:Configuration.py

示例10: appDataDir

# 需要导入模块: import appdirs [as 别名]
# 或者: from appdirs import AppDirs [as 别名]
def appDataDir(appName):
    """
    appDataDir returns an operating system specific directory to be used for
    storing application data for an application.
    """
    if appName == "" or appName == ".":
        return "."

    # The caller really shouldn't prepend the appName with a period, but
    # if they do, handle it gracefully by stripping it.
    appName = appName.lstrip(".")
    appNameUpper = appName.capitalize()
    appNameLower = appName.lower()

    # Get the OS specific home directory.
    homeDir = os.path.expanduser("~")

    # Fall back to standard HOME environment variable that works
    # for most POSIX OSes.
    if homeDir == "":
        homeDir = os.getenv("HOME")

    opSys = platform.system()
    if opSys == "Windows":
        # Windows XP and before didn't have a LOCALAPPDATA, so fallback
        # to regular APPDATA when LOCALAPPDATA is not set.
        return AppDirs(appNameUpper, "").user_data_dir

    elif opSys == "Darwin":
        if homeDir != "":
            return os.path.join(homeDir, "Library", "Application Support", appNameUpper)

    else:
        if homeDir != "":
            return os.path.join(homeDir, "." + appNameLower)

    # Fall back to the current directory if all else fails.
    return "." 
开发者ID:decred,项目名称:tinydecred,代码行数:40,代码来源:helpers.py

示例11: __init__

# 需要导入模块: import appdirs [as 别名]
# 或者: from appdirs import AppDirs [as 别名]
def __init__(
        self,
        appname,  # type: Text
        author=None,  # type: Optional[Text]
        version=None,  # type: Optional[Text]
        roaming=False,  # type: bool
        create=True,  # type: bool
    ):
        # type: (...) -> None
        self.app_dirs = AppDirs(appname, author, version, roaming)
        self._create = create
        super(_AppFS, self).__init__(
            getattr(self.app_dirs, self.app_dir), create=create
        ) 
开发者ID:PyFilesystem,项目名称:pyfilesystem2,代码行数:16,代码来源:appfs.py

示例12: main

# 需要导入模块: import appdirs [as 别名]
# 或者: from appdirs import AppDirs [as 别名]
def main():
    # Build default paths for files.
    dirs = appdirs.AppDirs('QHangups', 'QHangups')
    default_log_path = os.path.join(dirs.user_data_dir, 'hangups.log')
    default_token_path = os.path.join(dirs.user_data_dir, 'refresh_token.txt')

    # Setup command line argument parser
    parser = argparse.ArgumentParser(prog='qhangups',
                                     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('--token', default=default_token_path,
                        help='OAuth refresh token storage path')
    args = parser.parse_args()

    # Create all necessary directories.
    for path in [args.log, args.token]:
        directory = os.path.dirname(path)
        if directory and not os.path.isdir(directory):
            try:
                os.makedirs(directory)
            except OSError as e:
                sys.exit('Failed to create directory: {}'.format(e))

    # Setup logging
    log_level = logging.DEBUG if args.debug else logging.WARNING
    logging.basicConfig(filename=args.log, level=log_level, format=LOG_FORMAT)
    # asyncio's debugging logs are VERY noisy, so adjust the log level
    logging.getLogger('asyncio').setLevel(logging.WARNING)
    # ...and if we don't need Hangups debug logs, then uncomment this:
    # logging.getLogger('hangups').setLevel(logging.WARNING)

    # Setup QApplication
    app = QtWidgets.QApplication(sys.argv)
    app.setOrganizationName("QHangups")
    app.setOrganizationDomain("qhangups.eutopia.cz")
    app.setApplicationName("QHangups")
    app.setQuitOnLastWindowClosed(False)
    app.installTranslator(translator)
    app.installTranslator(qt_translator)

    # Start Quamash event loop
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    with loop:
        widget = QHangupsMainWidget(args.token)
        loop.run_forever() 
开发者ID:xmikos,项目名称:qhangups,代码行数:51,代码来源:__main__.py

示例13: main

# 需要导入模块: import appdirs [as 别名]
# 或者: from appdirs import AppDirs [as 别名]
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 e:
                sys.exit(_('Failed to create directory: {}').format(e))

    # 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 e:
            sys.exit(_('Failed to copy default config file: {}').format(e))

    configure_logging(args)

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

    # start the bot
    bot.run() 
开发者ID:hangoutsbot,项目名称:hangoutsbot,代码行数:56,代码来源:hangupsbot.py

示例14: main

# 需要导入模块: import appdirs [as 别名]
# 或者: from appdirs import AppDirs [as 别名]
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_token_path = os.path.join(dirs.user_data_dir, 'refresh_token.txt')
    default_config_path = os.path.join(dirs.user_data_dir, 'config.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('--token', default=default_token_path,
                        help=_('OAuth refresh token storage path'))
    parser.add_argument('--config', default=default_config_path,
                        help=_('config storage path'))
    parser.add_argument('--version', action='version', version='%(prog)s {}'.format(__version__),
                        help=_('show program\'s version number and exit'))
    args = parser.parse_args()

    # Create all necessary directories.
    for path in [args.log, args.token, args.config]:
        directory = os.path.dirname(path)
        if directory and not os.path.isdir(directory):
            try:
                os.makedirs(directory)
            except OSError as e:
                sys.exit(_('Failed to create directory: {}').format(e))

    # 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(__file__), 'config.json')),
                        args.config)
        except (OSError, IOError) as e:
            sys.exit(_('Failed to copy default config file: {}').format(e))

    # Configure logging
    log_level = logging.DEBUG if args.debug else logging.WARNING
    logging.basicConfig(filename=args.log, level=log_level, format=LOG_FORMAT)
    # asyncio's debugging logs are VERY noisy, so adjust the log level
    logging.getLogger('asyncio').setLevel(logging.WARNING)

    # Start Hangups bot
    bot = HangupsBot(args.token, args.config)
    bot.run() 
开发者ID:xmikos,项目名称:hangupsbot,代码行数:51,代码来源:__main__.py

示例15: __init__

# 需要导入模块: import appdirs [as 别名]
# 或者: from appdirs import AppDirs [as 别名]
def __init__(self, download_root=None, link_path=None, os_name=None, bitness=None):
        """
        Initializer for the class.  Accepts two optional parameters.

        :param download_root: Path where the web driver binaries will be downloaded.  If running as root in macOS or
                              Linux, the default will be '/usr/local/webdriver', otherwise python appdirs module will
                              be used to determine appropriate location if no value given.
        :param link_path: Path where the link to the web driver binaries will be created.  If running as root in macOS
                          or Linux, the default will be 'usr/local/bin', otherwise appdirs python module will be used
                          to determine appropriate location if no value give. If set "AUTO", link will be created into
                          first writeable directory in PATH. If set "SKIP", no link will be created.
        """

        if not bitness:
            self.bitness = '64' if sys.maxsize > 2 ** 32 else '32'  # noqa: KEK100
        else:
            self.bitness = bitness

        self.os_name = os_name or self.get_os_name()
        self.dirs = AppDirs('WebDriverManager', 'salabs_')
        base_path = self._get_basepath()
        self.download_root = download_root or base_path

        if link_path in [None, 'AUTO']:
            bin_location = 'bin'
            if _inside_virtualenv():
                if self.os_name == 'win' and 'CYGWIN' not in platform.system():
                    bin_location = 'Scripts'
                self.link_path = os.path.join(sys.prefix, bin_location)
            else:
                if self.os_name in ['mac', 'linux'] and os.geteuid() == 0:
                    self.link_path = '/usr/local/bin'
                else:
                    dir_in_path = None
                    if link_path == 'AUTO':
                        dir_in_path = self._find_bin()
                    self.link_path = dir_in_path or os.path.join(base_path, bin_location)
        elif link_path == 'SKIP':
            self.link_path = None
        else:
            self.link_path = link_path

        try:
            os.makedirs(self.download_root)
            LOGGER.info('Created download root directory: %s', self.download_root)
        except OSError:
            pass

        if self.link_path is not None:
            try:
                os.makedirs(self.link_path)
                LOGGER.info('Created symlink directory: %s', self.link_path)
            except OSError:
                pass 
开发者ID:rasjani,项目名称:webdrivermanager,代码行数:56,代码来源:webdrivermanager.py


注:本文中的appdirs.AppDirs方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。