How to use the xdg.BaseDirectory function in xdg

To help you get started, we’ve selected a few xdg examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ubuntu / ubuntu-make / tests / tools / __init__.py View on Github external
def change_xdg_path(key, value=None, remove=False):
    if value:
        os.environ[key] = value
    if remove:
        with suppress(KeyError):
            os.environ.pop(key)
    import umake.tools
    importlib.reload(xdg.BaseDirectory)
    with suppress(KeyError):
        umake.tools.Singleton._instances.pop(umake.tools.ConfigHandler)
    umake.tools.xdg_config_home = xdg.BaseDirectory.xdg_config_home
    umake.tools.xdg_data_home = xdg.BaseDirectory.xdg_data_home
github ju1ius / uxdgmenu / usr / lib / uxdgmenu / uxm / config.py View on Github external
PKG_NAME = "uxdgmenu"
APP_DAEMON = "uxm-daemon"
APP_WATCH = "uxdgmenud"
MENU_FILE = "uxm-applications.menu"
ROOTMENU_FILE = "uxm-rootmenu.menu"

HOME = os.path.expanduser('~')
BOOKMARKS_FILE = os.path.join(HOME, '.gtk-bookmarks')
RECENT_FILES_FILE = get_recent_files_path()

CACHE_DIR = os.path.join(xdg.BaseDirectory.xdg_cache_home, PKG_NAME)
CONFIG_DIR = os.path.join(xdg.BaseDirectory.xdg_config_home, PKG_NAME)
DATA_DIR = os.path.join(xdg.BaseDirectory.xdg_data_home, PKG_NAME)

APP_DIRS = [d for d in xdg.BaseDirectory.load_data_paths('applications')]
DIR_DIRS = [d for d in xdg.BaseDirectory.load_data_paths('desktop-directories')]
MENU_DIRS = [
    os.path.join(SYSCONFDIR, 'xdg', 'menus'),
    os.path.join(CONFIG_DIR, 'menus')
]

SYSTEM_CONFIG_FILE = os.path.join(SYSCONFDIR, PKG_NAME, 'menu.conf')
USER_CONFIG_FILE = os.path.join(CONFIG_DIR, 'menu.conf')

CACHE_DB = os.path.join(CACHE_DIR, 'cache.db')
ICON_CACHE_PATH = os.path.join(CACHE_DIR, 'icons')
APPS_CACHE = os.path.join(CACHE_DIR, 'applications')
BOOKMARKS_CACHE = os.path.join(CACHE_DIR, 'bookmarks')
RECENT_FILES_CACHE = os.path.join(CACHE_DIR, 'recent-files')
DEVICES_CACHE = os.path.join(CACHE_DIR, 'devices')
ROOTMENU_CACHE = os.path.join(CACHE_DIR, 'rootmenu')
github crossroadchurch / paul / openlp / core / common / applocation.py View on Github external
elif is_macosx():
        if dir_type == AppLocation.DataDir:
            return os.path.join(str(os.getenv('HOME')), 'Library', 'Application Support', 'openlp-paul', 'Data')
        elif dir_type == AppLocation.LanguageDir:
            return os.path.dirname(openlp.__file__)
        return os.path.join(str(os.getenv('HOME')), 'Library', 'Application Support', 'openlp-paul')
    else:
        if dir_type == AppLocation.LanguageDir:
            for prefix in ['/usr/local', '/usr']:
                directory = os.path.join(prefix, 'share', 'openlp-paul')
                if os.path.exists(directory):
                    return directory
            return os.path.join('/usr', 'share', 'openlp-paul')
        if XDG_BASE_AVAILABLE:
            if dir_type == AppLocation.DataDir:
                return os.path.join(str(BaseDirectory.xdg_data_home), 'openlp-paul')
            elif dir_type == AppLocation.CacheDir:
                return os.path.join(str(BaseDirectory.xdg_cache_home), 'openlp-paul')
        if dir_type == AppLocation.DataDir:
            return os.path.join(str(os.getenv('HOME')), '.openlp-paul', 'data')
        return os.path.join(str(os.getenv('HOME')), '.openlp-paul')
github obensonne / remuco / base / module / remuco / remos.py View on Github external
# =============================================================================
# locations
# =============================================================================

# media_dirs:
#    Maps some mimetypes to a list of locations which typically contain files
#    of a specific mimetype. For those mimetypes not mapped, `user_home` may
#    be used as a fallback.

if linux:
    
    import xdg.BaseDirectory

    user_home = os.getenv("HOME")
    user_config_dir = xdg.BaseDirectory.xdg_config_home
    user_cache_dir = xdg.BaseDirectory.xdg_cache_home

    media_dirs = {}
    try:
        with open(opj(user_config_dir, "user-dirs.dirs")) as fp:
            _udc = fp.read()
    except IOError, e:
        log.warning("failed to load user dirs config (%s)" % e)
        media_dirs["audio"] = ["~/Music"]
        media_dirs["video"] = ["~/Videos"]
    else:
        m = re.search(r'XDG_MUSIC_DIR="([^"]+)', _udc)
        media_dirs["audio"] = [m and m.groups()[0] or "~/Music"]
        m = re.search(r'XDG_VIDEOS_DIR="([^"]+)', _udc)
        media_dirs["video"] = [m and m.groups()[0] or "~/Video"]
github rndusr / torf-cli / torfcli / _cli.py View on Github external
from . import _config


class CLIError(Exception):
    def __init__(self, msg=None, error_code=None):
        self.errno = error_code
        if msg is None:
            if error_code is None:
                raise RuntimeError('Both msg and error_code are missing!')
            msg = os.strerror(error_code)
        super().__init__(f'{_vars.__appname__}: {msg}')


_DEFAULT_CREATOR = f'{_vars.__appname__}/{_vars.__version__}'
_VERSION_INFO = f'{_vars.__appname__} {_vars.__version__} <{_vars.__url__}>'
_DEFAULT_PROFILE_FILE = os.path.join(BaseDirectory.xdg_config_home, _vars.__appname__, 'config')
_HELP = f"""
{_VERSION_INFO}

Create, display and edit torrents

USAGE
    {_vars.__appname__} PATH [OPTIONS] [-o TORRENT]
    {_vars.__appname__} -i TORRENT
    {_vars.__appname__} -i TORRENT [OPTIONS] -o NEW TORRENT

ARGUMENTS
    PATH                   Path to torrent's content
    --in, -i TORRENT       Read metainfo from TORRENT
    --out, -o TORRENT      Write metainfo to TORRENT (default: NAME.torrent)
    --magnet, -m           Create magnet link
    --exclude, -e EXCLUDE  File matching pattern that is used to exclude
github chronitis / curseradio / curseradio / curseradio.py View on Github external
def load_favourites(self):
        for path in xdg.BaseDirectory.load_data_paths("curseradio"):
            opmlpath = pathlib.Path(path, "favourites.opml")
            if opmlpath.exists():
                return OPMLFavourites.from_xml(str(opmlpath))
        return OPMLFavourites("", {})
github geier / pycarddav / pycarddav / backend.py View on Github external
def __init__(self,
                 db_path=None,
                 encoding="utf-8",
                 errors="strict",
                 debug=False):
        if db_path is None:
            db_path = xdg.BaseDirectory.save_data_path('pycard') + 'abook.db'
        self.db_path = path.expanduser(db_path)
        self.conn = sqlite3.connect(self.db_path)
        self.cursor = self.conn.cursor()
        self.encoding = encoding
        self.errors = errors
        self.debug = debug
        self.display_all = False
        self.print_function = "print_contact_info"
        self._create_default_tables()
        self._check_table_version()
github bharadwaj-raju / libdesktop / libdesktop / get_config_dir.py View on Github external
if 'XDG_CONFIG_HOME' in os.environ:

		config_home = os.getenv('XDG_CONFIG_HOME')

	elif get_desktop_environment() == 'windows':

		import winreg

		config_home = winreg.ExpandEnvironmentStrings('%APPDATA%')

	else:

		try:

			from xdg import BaseDirectory
			config_home =  BaseDirectory.xdg_config_home

		except ImportError:  # Most likely a Linux/Unix system anyway

			config_home = os.path.expanduser('~/.config')

	if app_name == '':

		return config_home

	else:

		if os.path.isdir(os.path.join(config_home, app_name)):

			return os.path.join(config_home, app_name)

		else:
github sahib / libmunin / munin / caching.py View on Github external
def get_cache_path(extra_name=None):
    '''Tries to find out the XDG caching path of your system.

    This is done preferrably with PyXDG. If it's not installed,
    we try the XDG_CACHE_HOME environment variable or default to ~/.cache/

    If the path does not exist yet it will be created for you.

    :param extra_name: Extra path component to append to the path (or None).
    :returns: The full path, e.g.: /home/user/.cache/libmunin/
    '''
    if HAS_XDG and 0:
        base_dir = BaseDirectory.xdg_cache_home
    else:
        base_dir = os.environ.get('XDG_CACHE_HOME') or path.join(path.expanduser('~'), '.cache')

    base_dir = path.join(base_dir, 'libmunin')
    check_or_mkdir(base_dir)
    return base_dir if not extra_name else path.join(base_dir, extra_name)
github snapcore / snapcraft / snapcraft / config.py View on Github external
# That's why it's only checked for 'loading' and never written to.
            # Essentially, all authentication-related changes, like
            # login/logout or macaroon-refresh, will not be persisted for the
            # next runs.
            file_path = ""
            if os.path.exists(LOCAL_CONFIG_FILENAME):
                file_path = LOCAL_CONFIG_FILENAME

                # FIXME: We don't know this for sure when loading the config.
                # Need a better separation of concerns.
                logger.warn(
                    "Using local configuration ({!r}), changes will not be "
                    "persisted.".format(file_path)
                )
            else:
                file_path = BaseDirectory.load_first_config(
                    "snapcraft", "snapcraft.cfg"
                )
            if file_path and os.path.exists(file_path):
                with open(file_path, "r") as f:
                    config = f.read()

        if config:
            _load_potentially_base64_config(self.parser, config)