Python appdirs.AppDirs() Examples

The following are 15 code examples of appdirs.AppDirs(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module appdirs , or try the search function .
Example #1
Source File: settings.py    From bioservices with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #2
Source File: test_setup.py    From gphotos-sync with MIT License 6 votes vote down vote up
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 
Example #3
Source File: config.py    From AnyBlok with Mozilla Public License 2.0 6 votes vote down vote up
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) 
Example #4
Source File: util.py    From cti-stix-validator with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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() 
Example #5
Source File: common.py    From hangups with MIT License 6 votes vote down vote up
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 
Example #6
Source File: config.py    From AnyBlok with Mozilla Public License 2.0 5 votes vote down vote up
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() 
Example #7
Source File: web.py    From profanity-filter with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #8
Source File: telegram_send.py    From telegram-send with GNU General Public License v3.0 5 votes vote down vote up
def get_config_path():
    return AppDirs("telegram-send").user_config_dir + ".conf" 
Example #9
Source File: Configuration.py    From caller-lookup with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #10
Source File: helpers.py    From tinydecred with ISC License 5 votes vote down vote up
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 "." 
Example #11
Source File: appfs.py    From pyfilesystem2 with MIT License 5 votes vote down vote up
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
        ) 
Example #12
Source File: __main__.py    From qhangups with GNU General Public License v3.0 4 votes vote down vote up
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() 
Example #13
Source File: hangupsbot.py    From hangoutsbot with GNU Affero General Public License v3.0 4 votes vote down vote up
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() 
Example #14
Source File: __main__.py    From hangupsbot with GNU General Public License v3.0 4 votes vote down vote up
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() 
Example #15
Source File: webdrivermanager.py    From webdrivermanager with MIT License 4 votes vote down vote up
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