Python appdirs.user_data_dir() Examples

The following are 30 code examples of appdirs.user_data_dir(). 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: install.py    From dephell with MIT License 6 votes vote down vote up
def data_dir(self) -> Path:
        try:
            from appdirs import user_data_dir
        except ImportError:

            # linux
            path = Path.home() / '.local' / 'share'
            if path.exists():
                return path / 'dephell'

            # mac os
            path = Path.home() / 'Library' / 'Application Support'
            if path.exists():
                return path / 'dephell'

            self.pip_main(['install', 'appdirs'])
            from appdirs import user_data_dir

        return Path(user_data_dir('dephell')) 
Example #2
Source File: sqlite.py    From python-graphenelib with MIT License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        appauthor = "Fabian Schuh"
        appname = kwargs.get("appname", "graphene")
        data_dir = kwargs.get("data_dir", user_data_dir(appname, appauthor))

        if "profile" in kwargs:
            self.storageDatabase = "{}.sqlite".format(kwargs["profile"])
        else:
            self.storageDatabase = "{}.sqlite".format(appname)

        self.sqlite_file = os.path.join(data_dir, self.storageDatabase)

        """ Ensure that the directory in which the data is stored
            exists
        """
        if os.path.isdir(data_dir):  # pragma: no cover
            return
        else:  # pragma: no cover
            os.makedirs(data_dir) 
Example #3
Source File: storage.py    From piston-lib with MIT License 6 votes vote down vote up
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)) 
Example #4
Source File: conf.py    From lbry-sdk with MIT License 6 votes vote down vote up
def get_linux_directories() -> typing.Tuple[str, str, str]:
    try:
        with open(os.path.join(user_config_dir(), 'user-dirs.dirs'), 'r') as xdg:
            down_dir = re.search(r'XDG_DOWNLOAD_DIR=(.+)', xdg.read())
        if down_dir:
            down_dir = re.sub(r'\$HOME', os.getenv('HOME') or os.path.expanduser("~/"), down_dir.group(1))
            download_dir = re.sub('\"', '', down_dir)
    except OSError:
        download_dir = os.getenv('XDG_DOWNLOAD_DIR')
    if not download_dir:
        download_dir = os.path.expanduser('~/Downloads')

    # old
    data_dir = os.path.expanduser('~/.lbrynet')
    lbryum_dir = os.path.expanduser('~/.lbryum')
    if os.path.isdir(data_dir) or os.path.isdir(lbryum_dir):
        return data_dir, lbryum_dir, download_dir

    # new
    return user_data_dir('lbry/lbrynet'), user_data_dir('lbry/lbryum'), download_dir 
Example #5
Source File: conf.py    From lbry-sdk with MIT License 6 votes vote down vote up
def get_windows_directories() -> typing.Tuple[str, str, str]:
    from lbry.winpaths import get_path, FOLDERID, UserHandle, \
        PathNotFoundException  # pylint: disable=import-outside-toplevel

    try:
        download_dir = get_path(FOLDERID.Downloads, UserHandle.current)
    except PathNotFoundException:
        download_dir = os.getcwd()

    # old
    appdata = get_path(FOLDERID.RoamingAppData, UserHandle.current)
    data_dir = os.path.join(appdata, 'lbrynet')
    lbryum_dir = os.path.join(appdata, 'lbryum')
    if os.path.isdir(data_dir) or os.path.isdir(lbryum_dir):
        return data_dir, lbryum_dir, download_dir

    # new
    data_dir = user_data_dir('lbrynet', 'lbry')
    lbryum_dir = user_data_dir('lbryum', 'lbry')
    return data_dir, lbryum_dir, download_dir 
Example #6
Source File: gui.py    From sky3ds.py with MIT License 6 votes vote down vote up
def check_for_template(self):
        root.update_idletasks() #since this is run during view __init__ before mainloop finishes a loop we have to update tk() so it responds properly to input events.

        data_dir = user_data_dir('sky3ds', 'Aperture Laboratories')
        template_txt = os.path.join(data_dir, 'template.txt')

        if not os.path.isfile(template_txt):
            tkMessageBox.showinfo("Template.txt not found.", "Template.txt not found, please select a Sky3ds template file")
            update_template()
        else:
            pass 
Example #7
Source File: _appdirs.py    From learn_python3_spider with MIT License 6 votes vote down vote up
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) 
Example #8
Source File: default.py    From intake with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def load_combo_catalog():
    """Load a union of the user and global catalogs for convenience"""
    user_dir = user_data_dir()
    global_dir = global_data_dir()
    desc = 'Generated from data packages found on your intake search path'
    cat_dirs = []
    if os.path.isdir(user_dir):
        cat_dirs.append(user_dir + '/*.yaml')
        cat_dirs.append(user_dir + '/*.yml')
    if os.path.isdir(global_dir):
        cat_dirs.append(global_dir + '/*.yaml')
        cat_dirs.append(global_dir + '/*.yml')
    for path_dir in conf.get('catalog_path', []):
        if path_dir != '':
            if not path_dir.endswith(('yaml', 'yml')):
                cat_dirs.append(path_dir + '/*.yaml')
                cat_dirs.append(path_dir + '/*.yml')
            else:
                cat_dirs.append(path_dir)

    return YAMLFilesCatalog(cat_dirs, name='builtin', description=desc) 
Example #9
Source File: _appdirs.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #10
Source File: tellurium.py    From tellurium with Apache License 2.0 5 votes vote down vote up
def getAppDir():
    import os
    from sys import platform
    if platform == "linux" or platform == "linux2":
        return os.path.join(os.path.expanduser('~'), '.config', 'Tellurium')
    else:
        import appdirs
        return appdirs.user_data_dir('Tellurium', 'Tellurium') 
Example #11
Source File: box.py    From synthesizer with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self):
        super().__init__()
        self.config_location = appdirs.user_data_dir("PythonJukebox", "Razorvine")
        os.makedirs(self.config_location, mode=0o700, exist_ok=True)
        for family in tk.font.names():
            font = tk.font.nametofont(family)
            font["size"] = abs(font["size"]) + 1
            if family != "TkFixedFont":
                font["family"] = "helvetica"
        self.title("Jukebox   |   synthplayer lib v" + synthplayer.__version__)
        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) 
Example #12
Source File: musicfiledb.py    From synthesizer with GNU Lesser General Public License v3.0 5 votes vote down vote up
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
                );""") 
Example #13
Source File: storage.py    From piston-lib with MIT License 5 votes vote down vote up
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)) 
Example #14
Source File: common.py    From kotori with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self):
        if not ConfigStore.store:
            print "ConfigStoreShelve.__init__"
            self.app_data_dir = user_data_dir('kotori', 'daqzilla')
            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) 
Example #15
Source File: path.py    From AnkiTools with MIT License 5 votes vote down vote up
def get_collection_path(account_name: str=None):
    if account_name is None:
        account_name = 'User 1'

    collection_path = os.path.join(appdirs.user_data_dir('Anki2'), account_name, 'collection.anki2')
    return collection_path 
Example #16
Source File: util.py    From deepbgc with MIT License 5 votes vote down vote up
def get_default_downloads_dir():
    return user_data_dir("deepbgc", version="data") 
Example #17
Source File: config.py    From putio-automator with MIT License 5 votes vote down vote up
def init(site=False):
    "Prompt the user for config"

    if site:
        base_dir = appdirs.site_data_dir(APP_NAME, APP_AUTHOR)
    else:
        base_dir = appdirs.user_data_dir(APP_NAME, APP_AUTHOR)

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

    config_path = os.path.join(base_dir, 'config.py')

    incomplete = os.path.realpath(prompt('Incomplete directory', 'incomplete'))
    downloads = os.path.realpath(prompt('Downloads directory', 'downloads'))
    torrents = os.path.realpath(prompt('Torrents directory', 'torrents'))

    putio_token = prompt('OAuth Token')

    config_dist = find_config_dist()
    with open(config_dist, 'r') as source:
        contents = (source.read()
                    .replace("os.getenv('PUTIO_TOKEN')",
                             "os.getenv('PUTIO_TOKEN', '" + putio_token + "')")
                    .replace("/files/downloads", downloads)
                    .replace("/files/incomplete", incomplete)
                    .replace("/files/torrents", torrents))

        with open(config_path, 'w') as destination:
            destination.write(contents)

        os.chmod(config_path, stat.S_IRUSR | stat.S_IWUSR)

        print '\nConfig written to %s' % config_path 
Example #18
Source File: dirs.py    From aw-core with Mozilla Public License 2.0 5 votes vote down vote up
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 
Example #19
Source File: tinterface.py    From omnitool with MIT License 5 votes vote down vote up
def get_myterraria():
    import os

    if os.name == "nt":
        # get the my documents folder in windows. on other OS it will fail somewhere
        import ctypes

        dll = ctypes.windll.shell32
        buf = ctypes.create_unicode_buffer(300)
        dll.SHGetSpecialFolderPathW(None, buf, 0x0005, False)

        p = Path(buf.value) / "My Games" / "Terraria"
    else:
        p = appdirs.user_data_dir('Terraria')
    return Path(p) 
Example #20
Source File: installer.py    From python-qutescript with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 
Example #21
Source File: Bear.py    From coala with GNU Affero General Public License v3.0 5 votes vote down vote up
def data_dir(cls):
        """
        Returns a directory that may be used by the bear to store stuff. Every
        bear has an own directory dependent on their name.
        """
        data_dir = abspath(join(user_data_dir('coala-bears'), cls.name))

        makedirs(data_dir, exist_ok=True)
        return data_dir 
Example #22
Source File: Bear.py    From coala with GNU Affero General Public License v3.0 5 votes vote down vote up
def data_dir(cls):
        """
        Returns a directory that may be used by the bear to store stuff. Every
        bear has an own directory dependent on their name.
        """
        data_dir = abspath(join(user_data_dir('coala-bears'), cls.name))

        makedirs(data_dir, exist_ok=True)
        return data_dir 
Example #23
Source File: fileIO.py    From openMotor with GNU General Public License v3.0 5 votes vote down vote up
def getConfigPath(): # Returns the path that files like preferences and propellant library should be in
    if platform.system() == 'Darwin': # On OSX, the configuration files should live in the library
        path = appdirs.user_data_dir('openMotor', 'openMotor')
        if not os.path.isdir(path): # Create directory if it doesn't exist
            os.mkdir(path)
        return path + '/'
    # On other platforms they can live in this directory
    return '' 
Example #24
Source File: downloads.py    From mhcflurry with Apache License 2.0 5 votes vote down vote up
def configure():
    """
    Setup various global variables based on environment variables.
    """
    global _DOWNLOADS_DIR
    global _CURRENT_RELEASE

    _CURRENT_RELEASE = None
    _DOWNLOADS_DIR = environ.get("MHCFLURRY_DOWNLOADS_DIR")
    if not _DOWNLOADS_DIR:
        metadata = get_downloads_metadata()
        _CURRENT_RELEASE = environ.get("MHCFLURRY_DOWNLOADS_CURRENT_RELEASE")
        if not _CURRENT_RELEASE:
            _CURRENT_RELEASE = metadata['current-release']

        current_release_compatability = (
            metadata["releases"][_CURRENT_RELEASE]["compatibility-version"])
        current_compatability = metadata["current-compatibility-version"]
        if current_release_compatability != current_compatability:
            logging.warning(
                "The specified downloads are not compatible with this version "
                "of the MHCflurry codebase. Downloads: release %s, "
                "compatability version: %d. Code compatability version: %d",
                _CURRENT_RELEASE,
                current_release_compatability,
                current_compatability)

        data_dir = environ.get("MHCFLURRY_DATA_DIR")
        if not data_dir:
            # increase the version every time we make a breaking change in
            # how the data is organized. For changes to e.g. just model
            # serialization, the downloads release numbers should be used.
            data_dir = user_data_dir("mhcflurry", version="4")
        _DOWNLOADS_DIR = join(data_dir, _CURRENT_RELEASE)

    logging.debug("Configured MHCFLURRY_DOWNLOADS_DIR: %s", _DOWNLOADS_DIR) 
Example #25
Source File: __init__.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def chdir_to_data_directory():
    if not is_independent_package():
        # Do nothing.
        return

    import appdirs
    import os
    app_data_dir: str = appdirs.user_data_dir("Hummingbot", "hummingbot.io")
    os.makedirs(os.path.join(app_data_dir, "logs"), 0o711, exist_ok=True)
    os.makedirs(os.path.join(app_data_dir, "conf"), 0o711, exist_ok=True)
    os.chdir(app_data_dir)
    set_prefix_path(app_data_dir) 
Example #26
Source File: conf.py    From lbry-sdk with MIT License 5 votes vote down vote up
def get_darwin_directories() -> typing.Tuple[str, str, str]:
    data_dir = user_data_dir('LBRY')
    lbryum_dir = os.path.expanduser('~/.lbryum')
    download_dir = os.path.expanduser('~/Downloads')
    return data_dir, lbryum_dir, download_dir 
Example #27
Source File: default.py    From intake with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def load_user_catalog():
    """Return a catalog for the platform-specific user Intake directory"""
    cat_dir = user_data_dir()
    if not os.path.isdir(cat_dir):
        return Catalog()
    else:
        return YAMLFilesCatalog(cat_dir) 
Example #28
Source File: default.py    From intake with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def user_data_dir():
    """Return the user Intake catalog directory"""
    return appdirs.user_data_dir(appname='intake', appauthor='intake') 
Example #29
Source File: test_top_level.py    From intake with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def user_catalog():
    target_catalog = copy_test_file('catalog1.yml',
                                    appdirs.user_data_dir(appname='intake',
                                                          appauthor='intake'))
    yield target_catalog
    # Remove the file, but not the directory (because there might be other
    # files already there)
    os.remove(target_catalog) 
Example #30
Source File: production.py    From cachebrowser with MIT License 5 votes vote down vote up
def data_dir(self):
        return appdirs.user_data_dir(APP_NAME)