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

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

项目:FuME    作者:fupadev    | 项目源码 | 文件源码
def read_settings(self):
        self.settings = QtCore.QSettings('fume', 'Match-Explorer')

        self.resize(self.settings.value('mainwindow/size', self.size()))
        try:
            self.move(self.settings.value('mainwindow/pos'))
        except:
            pass

        self.actionZeitraum.setChecked(self.settings.value('menubar/date/range', True, bool))
        self.actionZeitpunkt.setChecked(self.settings.value('menubar/date/day', False, bool))

        now = datetime.datetime.now()
        self.dateEdit_3.setDate(self.settings.value('date_from_calendar', QtCore.QDate(now.year, now.month, now.day)))
        self.dateEdit_4.setDate(self.settings.value('date_to_calendar', QtCore.QDate(now.year, now.month, now.day)))

        # dbPaths
        # Windows: ?C:\Users\<User>\AppData\Local\FuME\FuME
        # macOS: /Users/<User>/Library/Application Support/FuME
        userDataDir = appdirs.user_data_dir('FuME', 'FuME')
        src = self.get_pathToTemp(['db', 'sql_default.db'])
        dst = os.path.join(userDataDir, 'sql.db')
        if not os.path.exists(userDataDir):
            os.makedirs(userDataDir)
            shutil.copy(src, dst)
        self.dbPath = dst
项目:sweetshot    作者:AnCh7    | 项目源码 | 文件源码
def check_legacy_v2(self):
        """ Look for legacy wallet and move to new directory
        """
        appname = "steem"
        appauthor = "Fabian Schuh"
        storageDatabase = "steem.sqlite"
        data_dir = user_data_dir(appname, appauthor)
        sqlDataBaseFile = os.path.join(data_dir, storageDatabase)

        if os.path.isdir(data_dir) and not os.path.exists(self.sqlDataBaseFile):
            # Move whole directory
            try:
                shutil.copytree(data_dir, self.data_dir)
            except FileExistsError:
                pass
            # Copy piston.sql to steem.sql (no deletion!)
            shutil.copy(sqlDataBaseFile, self.sqlDataBaseFile)
            log.info("Your settings have been moved to {}".format(self.sqlDataBaseFile))
项目:myriagon    作者:hawkowl    | 项目源码 | 文件源码
def load_tasks():

    dest = FilePath(appdirs.user_data_dir("myriagon", "hawkowl"))
    task_file = dest.child("tasks.json")

    if not task_file.exists():
        dest.makedirs(True)
        task_file.setContent(b"[]")

    loaded = cattr.loads(
        json.loads(task_file.getContent().decode('utf8')),
        List[Task])

    def sort(x):
        time = load_time_spent(x)
        return get_time_needed_for_session(x) - get_time_for_session(x, time)

    loaded.sort(key=sort, reverse=True)
    return loaded
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def getDataDirectory(moduleName=None):
    """
    Get a data directory for the caller function, or C{moduleName} if given.

    @param moduleName: The module name if you don't wish to have the caller's
        module.
    @type moduleName: L{str}

    @returns: A directory for putting data in.
    @rtype: L{str}
    """
    if not moduleName:
        caller = currentframe(1)
        moduleName = inspect.getmodule(caller).__name__

    return appdirs.user_data_dir(moduleName)
项目:piston-lib    作者:xeroc    | 项目源码 | 文件源码
def check_legacy_v2(self):
        """ Look for legacy wallet and move to new directory
        """
        appname = "steem"
        appauthor = "Fabian Schuh"
        storageDatabase = "steem.sqlite"
        data_dir = user_data_dir(appname, appauthor)
        sqlDataBaseFile = os.path.join(data_dir, storageDatabase)

        if os.path.isdir(data_dir) and not os.path.exists(self.sqlDataBaseFile):
            # Move whole directory
            try:
                shutil.copytree(data_dir, self.data_dir)
            except FileExistsError:
                pass
            # Copy piston.sql to steem.sql (no deletion!)
            shutil.copy(sqlDataBaseFile, self.sqlDataBaseFile)
            log.info("Your settings have been moved to {}".format(self.sqlDataBaseFile))
项目:pyomo    作者:Pyomo    | 项目源码 | 文件源码
def __init__(self):
        self._options_stack = [ default_pyomo_config() ]

        # Load the user's configuration
        sources = [(json.load, 'json')]
        if yaml_available:
            sources.append( (yaml.load, 'yml') )
            sources.append( (yaml.load, 'yaml') )
        for parser, suffix in sources:
            cfg_file = os.path.join( appdirs.user_data_dir('pyomo'),
                                     'config.'+suffix)
            if os.path.exists(cfg_file):
                fp = open(cfg_file)
                try:
                    data = parser(fp)
                except:
                    logger.error("Error parsing the user's default "
                                 "configuration file\n\t%s." % (cfg_file,))
                self._options_stack[0].set_value(data)
项目:pyupdater-wx-demo    作者:wettenhj    | 项目源码 | 文件源码
def tearDown(self):
        """
        Clean up.
        """
        wxupdatedemo.__version__ = self.originalVersion
        try:
            shutil.rmtree(self.tempDir)
        except OSError:
            logger.warning("Couldn't remove %s", self.tempDir)
        os.chdir(self.initialWorkingDir)
        try:
            shutil.rmtree(self.fileServerDir)
        except OSError:
            logger.warning("Couldn't remove %s", self.fileServerDir)
        del os.environ['PYUPDATER_FILESERVER_DIR']
        del os.environ['WXUPDATEDEMO_TESTING']
        del os.environ['WXUPDATEDEMO_TESTING_FROZEN']
        del os.environ['WXUPDATEDEMO_TESTING_APP_NAME']
        del os.environ['WXUPDATEDEMO_TESTING_COMPANY_NAME']
        del os.environ['WXUPDATEDEMO_TESTING_APP_VERSION']
        del os.environ['WXUPDATEDEMO_TESTING_PUBLIC_KEY']
        if os.path.exists(appdirs.user_data_dir(APP_NAME, COMPANY_NAME)):
            try:
                shutil.rmtree(appdirs.user_data_dir(APP_NAME, COMPANY_NAME))
            except OSError:
                logger.warning("Couldn't remove %s",
                               appdirs.user_data_dir(APP_NAME, COMPANY_NAME))
项目:wurst    作者:IndEcol    | 项目源码 | 文件源码
def get_base_directory():
    """Return base directory where cache and output data are saved.

    Creates directory if it is not already present."""
    return create_dir(appdirs.user_data_dir("Wurst", "WurstTeam"))
项目:nucypher-kms    作者:nucypher    | 项目源码 | 文件源码
def __init__(self, path=None):
        self.path = path or os.path.join(
                appdirs.user_data_dir(CONFIG_APPNAME), DB_NAME)
        db_dir = os.path.dirname(self.path)
        if not os.path.exists(db_dir):
            os.makedirs(db_dir)

        self.db = lmdb.open(self.path)
        # XXX removal when expired? Indexing by time?
项目:nucypher-kms    作者:nucypher    | 项目源码 | 文件源码
def pytest_runtest_teardown(item, nextitem):
    path = os.path.join(
            appdirs.user_data_dir(nkms.db.CONFIG_APPNAME), nkms.db.DB_NAME)
    if os.path.exists(path):
        shutil.rmtree(path)
项目:mccdl    作者:jkoelndorfer    | 项目源码 | 文件源码
def configure_argparser(self):
        a = self.argparser
        a.add_argument(
            "-c", "--cache-directory", type=str, default=str(CurseForgeClient.DEFAULT_CACHE_DIR),
            help="Path to directory to cache mccdl files. Defaults to %(default)s."
        )
        a.add_argument(
            "-l", "--log-level", type=str, default="info",
            choices=("debug", "info", "warning", "error", "critical"),
            help="Log level to use  for this run. Defaults to %(default)s."
        )
        a.add_argument(
            "--upgrade", action="store_true", default=False,
            help="If specified, allow upgrading an existing modpack instance."
        )
        a.add_argument(
            "--multimc-directory", type=str, default=appdirs.user_data_dir("multimc5"),
            help="Path to the MultiMC directory. Defaults to %(default)s."
        )
        a.add_argument(
            "modpack_url", type=str,
            help="Link to the modpack on Minecraft CurseForge."
        )
        a.add_argument(
            "instance_name", type=str,
            help="Name of the MultiMC instance to create."
        )
项目:ChemDataExtractor    作者:mcs07    | 项目源码 | 文件源码
def get_data_dir():
    """Return path to the data directory."""
    # Use data_dir config value if set, otherwise use OS-dependent data directory given by appdirs
    return config.get('data_dir', appdirs.user_data_dir('ChemDataExtractor'))
项目:FuME    作者:fupadev    | 项目源码 | 文件源码
def deleteDatabase(self):
        appdir = appdirs.user_data_dir('FuME', 'FuME')
        ret = QtWidgets.QMessageBox.critical(self, QtWidgets.qApp.tr("Datenbank löschen"),
                                             QtWidgets.qApp.tr("Willst du wirklich die Datenbank von FuME löschen? "
                                                               "Alle importierten Spiele gehen verloren.\n\n"
                                                               "Drücke OK um zu bestätigen und Abbrechen um zurückzukehren."),
                                             QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)
        if ret == QtWidgets.QMessageBox.Ok:
            QtWidgets.QMessageBox.critical(self, QtWidgets.qApp.tr("Datenbank löschen"),
                                           QtWidgets.qApp.tr("Die Datenbank wird gelöscht und das Programm beendet.\n\n"
                                                             "Nach dem Beenden sind alle Spiele entfernt."),
                                           QtWidgets.QMessageBox.Ok)
            self.parent().close()
            shutil.rmtree(appdir)
项目:python-qutescript    作者:hiway    | 项目源码 | 文件源码
def link_to_qutebrowser_userscripts_directory(path, name):
    import appdirs
    appdir = appdirs.user_data_dir('qutebrowser', 'qutebrowser')
    userscripts_dir = os.path.join(appdir, 'userscripts')
    userscripts_path = os.path.join(userscripts_dir, name)
    interpreter = get_interpreter()
    if not os.path.exists(userscripts_dir):
        os.makedirs(userscripts_dir, exist_ok=False)
    with open(userscripts_path, 'w') as bin_file:
        bin_file.write(LOADER_TEMPLATE.format(
            interpreter=interpreter,
            path=path,
        ))
    setup_permissions(userscripts_path)
    return userscripts_path
项目:sweetshot    作者:AnCh7    | 项目源码 | 文件源码
def check_legacy_v1(self):
        """ Look for legacy wallet and move to new directory
        """
        appname = "piston"
        appauthor = "Fabian Schuh"
        storageDatabase = "piston.sqlite"
        data_dir = user_data_dir(appname, appauthor)
        sqlDataBaseFile = os.path.join(data_dir, storageDatabase)

        if os.path.isdir(data_dir) and not os.path.isdir(self.data_dir):
            # Move whole directory
            shutil.copytree(data_dir, self.data_dir)
            # Copy piston.sql to steem.sql (no deletion!)
            shutil.copy(sqlDataBaseFile, self.sqlDataBaseFile)
            log.info("Your settings have been moved to {}".format(self.data_dir))
项目:sweetshot    作者:AnCh7    | 项目源码 | 文件源码
def check_legacy_v1(self):
        """ Look for legacy wallet and move to new directory
        """
        appname = "piston"
        appauthor = "Fabian Schuh"
        storageDatabase = "piston.sqlite"
        data_dir = user_data_dir(appname, appauthor)
        sqlDataBaseFile = os.path.join(data_dir, storageDatabase)

        if os.path.isdir(data_dir) and not os.path.isdir(self.data_dir):
            # Move whole directory
            shutil.copytree(data_dir, self.data_dir)
            # Copy piston.sql to steem.sql (no deletion!)
            shutil.copy(sqlDataBaseFile, self.sqlDataBaseFile)
            log.info("Your settings have been moved to {}".format(self.data_dir))
项目:myriagon    作者:hawkowl    | 项目源码 | 文件源码
def load_time_spent(task):

    dest = FilePath(appdirs.user_data_dir("myriagon", "hawkowl")).child("time")
    dest.makedirs(True)

    task_time_file = dest.child(str(task.id) + ".json")

    if not task_time_file.exists():
        dest.makedirs(True)
        task_time_file.setContent(b"[]")

    return cattr.loads(
        json.loads(task_time_file.getContent().decode('utf8')),
        List[TimeSpent])
项目:myriagon    作者:hawkowl    | 项目源码 | 文件源码
def save_time_spent(task, time):

    dest = FilePath(appdirs.user_data_dir("myriagon", "hawkowl")).child("time")
    dest.makedirs(True)

    task_time_file = dest.child(str(task.id) + ".json")
    task_time_file.setContent(json.dumps(cattr.dumps(time)).encode('utf8'))
项目:myriagon    作者:hawkowl    | 项目源码 | 文件源码
def save_tasks(tasks):

    dest = FilePath(appdirs.user_data_dir("myriagon", "hawkowl"))
    dest.makedirs(True)

    task_file = dest.child("tasks.json")
    task_file.setContent(json.dumps(cattr.dumps(tasks)).encode('utf8'))
项目:pypjlink    作者:gaetano-guerriero    | 项目源码 | 文件源码
def resolve_projector(projector):
    password = None

    # host:port
    if projector is not None and ':' in projector:
        host, port = projector.rsplit(':', 1)
        port = int(port)

    # maybe defined in config
    else:
        appdir = appdirs.user_data_dir('pjlink')
        conf_file = path.join(appdir, 'pjlink.conf')

        try:
            config = ConfigParser({'port': '4352', 'password': ''})
            with open(conf_file, 'r') as f:
                config.readfp(f)

            section = projector
            if projector is None:
                section = 'default'

            host = config.get(section, 'host')
            port = config.getint(section, 'port')
            password = config.get(section, 'password') or None

        except (NoSectionError, IOError):
            if projector is None:
                raise KeyError('No default projector defined in %s' % conf_file)

            # no config file, or no projector defined for this host
            # thus, treat the projector as a hostname w/o port
            host = projector
            port = 4352


    return host, port, password
项目:AerisCloud    作者:AerisCloud    | 项目源码 | 文件源码
def data_dir():
    return user_data_dir(app_name, app_author)
项目:envmgr-cli    作者:trainline    | 项目源码 | 文件源码
def get_filepath(cluster, env, is_refresh=False):
        app_dir = user_data_dir('envmgr', 'trainline')
        filename = 'patch_{0}_{1}'.format(cluster.lower(), env.lower())
        if is_refresh:
            filename += '_refresh'
        filename = '{0}.json'.format(sha1(filename.encode('utf-8')).hexdigest())
        return os.path.join(app_dir, filename)
项目: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
项目:beradio    作者:hiveeyes    | 项目源码 | 文件源码
def __init__(self):
        self.app_data_dir = user_data_dir(self.appname)
        #print >>sys.stderr, "ConfigStoreJson app_data_dir:", self.app_data_dir
        if not os.path.exists(self.app_data_dir):
            os.makedirs(self.app_data_dir)
        self.config_file = os.path.join(self.app_data_dir, 'config.json')
        #print >>sys.stderr, "ConfigStoreJson config_file:", self.config_file

        self.setup()
项目:althea    作者:benneely    | 项目源码 | 文件源码
def __init__(self,model_uuid):
        self.database = os.path.join(appdirs.user_data_dir(__app__),__filename__)
        self.model_uuid = model_uuid
        conn = sqlite3.connect(self.database)
        conn.row_factory = dict_factory
        c = conn.cursor()
        sql = "select input_uuid, type, variable_name, elicit_question from inputs where model_uuid=?"
        c.execute(sql,[(self.model_uuid)])
        metadata = c.fetchall()
        if len(metadata)==0:
            raise ValueError('The model_uuid provided is not in the database.')    
        sql = "select name,response, doi, implementation_file from models where model_uuid=?"
        c.execute(sql,[(self.model_uuid)])
        model = c.fetchall()
        self.model_name = model[0].get('name')     
        self.doi = model[0].get('doi')
        self.score_file = model[0].get('implementation_file')
        self.response = model[0].get('response')
        def __model_input_choices(input_uuid):
            sql = "select display_text from choices where input_uuid=?"
            c.execute(sql,[(input_uuid)])
            results = c.fetchall()
            return [x.get('display_text') for x in results]
        self.ask = {x.get('elicit_question'): __model_input_choices(x.get('input_uuid')) for x in metadata}
        self.parameter_name = [x.get('variable_name') for x in metadata]
        self.variable_type = [x.get('type') for x in metadata]
        c.close()
        conn.close()
项目:kotori    作者:daq-tools    | 项目源码 | 文件源码
def __init__(self):
        if not ConfigStore.store:
            print "ConfigStoreShelve.__init__"
            self.app_data_dir = user_data_dir('kotori', 'elmyra')
            if not os.path.exists(self.app_data_dir):
                os.makedirs(self.app_data_dir)
            self.config_file = os.path.join(self.app_data_dir, 'config')
            ConfigStore.store = shelve.open(self.config_file, writeback=True)
项目:kotori    作者:daq-tools    | 项目源码 | 文件源码
def __init__(self):
        if not ConfigStoreJson.store:
            #print "ConfigStoreJson.__init__"
            self.app_data_dir = user_data_dir('kotori-daq', 'Elmyra')
            logger.debug("ConfigStoreJson app_data_dir: {}".format(self.app_data_dir))
            if not os.path.exists(self.app_data_dir):
                os.makedirs(self.app_data_dir)
            self.config_file = os.path.join(self.app_data_dir, 'config.json')
            ConfigStoreJson.store = json_store.open(self.config_file)
项目:lbry-android    作者:lbryio    | 项目源码 | 文件源码
def default_storage_dir(self):
        udd = user_data_dir('python-for-android')
        if ' ' in udd:
            udd = '~/.python-for-android'
        return udd
项目:pandarus    作者:cmutel    | 项目源码 | 文件源码
def get_appdirs_path(subdir):
    """Get path for an ``appdirs`` directory, with subdirectory ``subdir``.

    Returns the full directory path."""
    dirpath = os.path.join(
        appdirs.user_data_dir("pandarus", "pandarus-cache"),
        subdir
    )
    if not os.path.isdir(dirpath):
        os.makedirs(dirpath)
    return os.path.abspath(dirpath)
项目:piston-lib    作者:xeroc    | 项目源码 | 文件源码
def check_legacy_v1(self):
        """ Look for legacy wallet and move to new directory
        """
        appname = "piston"
        appauthor = "Fabian Schuh"
        storageDatabase = "piston.sqlite"
        data_dir = user_data_dir(appname, appauthor)
        sqlDataBaseFile = os.path.join(data_dir, storageDatabase)

        if os.path.isdir(data_dir) and not os.path.isdir(self.data_dir):
            # Move whole directory
            shutil.copytree(data_dir, self.data_dir)
            # Copy piston.sql to steem.sql (no deletion!)
            shutil.copy(sqlDataBaseFile, self.sqlDataBaseFile)
            log.info("Your settings have been moved to {}".format(self.data_dir))
项目:aw-core    作者:ActivityWatch    | 项目源码 | 文件源码
def get_data_dir(module_name: Optional[str]) -> str:
    data_dir = appdirs.user_data_dir("activitywatch")
    return os.path.join(data_dir, module_name) if module_name else data_dir
项目:synthesizer    作者:irmen    | 项目源码 | 文件源码
def __init__(self, dbfile=None, scan_changes=True, silent=False):
        if not dbfile:
            dblocation = appdirs.user_data_dir("PythonJukebox", "Razorvine")
            os.makedirs(dblocation, mode=0o700, exist_ok=True)
            dbfile = os.path.join(dblocation, "tracks.sqlite")
        dbfile = os.path.abspath(dbfile)
        self.dbfile = dbfile
        self.dbconn = sqlite3.connect(dbfile, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
        self.dbconn.row_factory = sqlite3.Row   # make sure we can get results by column name
        self.dbconn.execute("PRAGMA foreign_keys=ON")
        try:
            self.dbconn.execute("SELECT COUNT(*) FROM tracks").fetchone()
            if not silent:
                print("Connected to database.")
                print("Database file:", dbfile)
            if scan_changes:
                self.scan_changes()
        except sqlite3.OperationalError:
            # the table does not yet exist, create the schema
            if not silent:
                print("Creating new database.")
                print("Database file:", dbfile)
            self.dbconn.execute("""CREATE TABLE tracks
                (
                    id integer PRIMARY KEY,
                    title nvarchar(260),
                    artist nvarchar(260),
                    album nvarchar(260),
                    year int,
                    genre nvarchar(100),
                    duration real NOT NULL,
                    modified timestamp NOT NULL,
                    location nvarchar(500) NOT NULL,
                    hash char(40) NOT NULL UNIQUE
                );""")
项目:synthesizer    作者:irmen    | 项目源码 | 文件源码
def __init__(self):
        super().__init__()
        self.config_location = appdirs.user_data_dir("PythonJukebox", "Razorvine")
        os.makedirs(self.config_location, mode=0o700, exist_ok=True)
        default_font = tk.font.nametofont("TkDefaultFont")
        default_font["size"] = abs(default_font["size"])+2
        default_font = tk.font.nametofont("TkTextFont")
        default_font["size"] = abs(default_font["size"])+2
        self.title("Jukebox")
        f = ttk.Frame()
        f1 = ttk.Frame(f)
        self.firstTrackFrame = TrackFrame(f1, "Track 1")
        self.secondTrackFrame = TrackFrame(f1, "Track 2")
        self.levelmeterFrame = LevelmeterFrame(f1)
        self.playlistFrame = PlaylistFrame(self, f1)
        self.firstTrackFrame.pack(side=tk.LEFT, fill=tk.Y)
        self.secondTrackFrame.pack(side=tk.LEFT, fill=tk.Y)
        self.levelmeterFrame.pack(side=tk.LEFT, fill=tk.Y)
        self.playlistFrame.pack(side=tk.LEFT, fill=tk.Y)
        f1.pack(side=tk.TOP)
        f2 = ttk.Frame(f)
        self.searchFrame = SearchFrame(self, f2)
        self.searchFrame.pack()
        f2.pack(side=tk.TOP)
        f3 = ttk.Frame(f)
        optionsFrame = ttk.Frame(f3)
        ttk.Button(optionsFrame, text="Database Config", command=self.do_database_config).pack()
        optionsFrame.pack(side=tk.LEFT)
        self.effectsFrame = EffectsFrame(self, f3)
        self.effectsFrame.pack()
        f3.pack(side=tk.TOP)
        self.statusbar = ttk.Label(f, text="<status>", relief=tk.GROOVE, anchor=tk.CENTER)
        self.statusbar.pack(fill=tk.X, expand=True)
        f.pack()
        self.player = Player(self, (self.firstTrackFrame, self.secondTrackFrame))
        self.backend = None
        self.backend_process = None
        self.show_status("Connecting to backend file service...")
        self.after(500, self.connect_backend)
项目:coincurve    作者:ofek    | 项目源码 | 文件源码
def main():
    here = os.path.dirname(os.path.abspath(__file__))
    os.chdir(here)

    version = sys.argv[-1]
    delete = not not sys.argv[-2] == '-d'
    delete_only = not not sys.argv[-2] == '--d'

    try:
        subprocess.call('git -h')
        git_path = 'git'
    except:
        git_path = None

    # Assume Windows portable Git
    if git_path is None:
        github_dir = os.path.join(appdirs.user_data_dir(), 'GitHub')
        for d in os.listdir(github_dir):
            if d.startswith('PortableGit'):
                git_path = os.path.join(github_dir, d, 'cmd', 'git.exe')

    if git_path is None:
        raise OSError('Unable to find git executable.')

    cmds = [
        '{0} tag -a {1} -m "Version {1}"'.format(git_path, version),
        '{} push origin {}'.format(git_path, version)
    ]
    delete_cmd = '{} tag -d {}'.format(git_path, version)

    if delete:
        cmds.insert(0, delete_cmd)
    elif delete_only:
        cmds = [delete_cmd]

    for cmd in cmds:
        subprocess.call(cmd)

    print(cmds)