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


Python xdg.BaseDirectory类代码示例

本文整理汇总了Python中xdg.BaseDirectory的典型用法代码示例。如果您正苦于以下问题:Python BaseDirectory类的具体用法?Python BaseDirectory怎么用?Python BaseDirectory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: __init__

    def __init__(self, release):
        self.release = release
        self.name = 'apt-venv'
        self.config = _loadJSON(open('/etc/apt-venv.conf'))

        self.distro = None
        for distro in self.config['distributions']:
            if self.release in self.config['distributions'][distro]['releases']:
                self.distro = distro
        if not self.distro:
            base = "Release \"{}\" not valid. ".format(self.release)
            if not self.release:
                base = "No release declared. "
            all_releases = []
            for distro in sorted(self.config['distributions'].keys()):
                releases = self.config['distributions'][distro]['releases']
                all_releases.append(" [%s] %s" % (distro, ' - '.join(releases)))
            raise ValueError(base +
                             "Please specify one of:\n%s" %
                             '\n'.join(all_releases))
        self.config_path = _BaseDirectory.save_config_path(self.name)
        self.cache_path = _BaseDirectory.save_cache_path(self.name)
        self.data_path = _BaseDirectory.save_data_path(self.name)
        self.config_path = _os.path.join(self.config_path, self.release)
        self.cache_path = _os.path.join(self.cache_path, self.release)
        self.data_path = _os.path.join(self.data_path, self.release)

        self.bashrc = _os.path.join(self.config_path, "bash.rc")
        self.sourceslist = _os.path.join(self.config_path, "sources.list")
        self.aptconf = _os.path.join(self.config_path, "apt.conf")
开发者ID:alessio,项目名称:apt-venv,代码行数:30,代码来源:__init__.py

示例2: __init__

    def __init__(self, sender=None, addresses=[], *args, **kwargs):
        super().__init__(*args, **kwargs)

        if not isinstance(addresses, list):
            addresses = [addresses]
        elif not addresses:
            import xdg.BaseDirectory as xdgb

            p = xdgb.load_first_config('notifier', 'addresses')
            if p is not None:
                with open(p, 'r') as f:
                    addresses = f.read().split()
            if not addresses:
                raise ValueError('No email addresses (defaults are read from {}/addresses, one address per line)'
                                 .format(xdgb.save_config_path('notifier')))
        for addr in addresses:
            if not isinstance(addr, str) or not '@' in addr:
                raise TypeError('`addresses` must be an email address or a list of email addresses')
        self._addresses = addresses

        if sender is None:
            sender = 'Notifier'
        self._sender = sender

        self._addr = '[email protected]{}'.format(platform.node())
开发者ID:kirelagin,项目名称:pynotifier,代码行数:25,代码来源:email.py

示例3: _cache_database

def _cache_database():
    global globs, magic, aliases, inheritance, _cache_uptodate

    _cache_uptodate = True

    aliases = {}  # Maps alias Mime types to canonical names
    inheritance = defaultdict(set)  # Maps to sets of parent mime types.

    # Load aliases
    for path in BaseDirectory.load_data_paths(os.path.join("mime", "aliases")):
        with open(path, "r") as f:
            for line in f:
                alias, canonical = line.strip().split(None, 1)
                aliases[alias] = canonical

    # Load filename patterns (globs)
    globs = GlobDB()
    for path in BaseDirectory.load_data_paths(os.path.join("mime", "globs2")):
        globs.merge_file(path)
    globs.finalise()

    # Load magic sniffing data
    magic = MagicDB()
    for path in BaseDirectory.load_data_paths(os.path.join("mime", "magic")):
        magic.merge_file(path)
    magic.finalise()

    # Load subclasses
    for path in BaseDirectory.load_data_paths(os.path.join("mime", "subclasses")):
        with open(path, "r") as f:
            for line in f:
                sub, parent = line.strip().split(None, 1)
                inheritance[sub].add(parent)
开发者ID:0312birdzhang,项目名称:pyxdg,代码行数:33,代码来源:Mime.py

示例4: __init__

 def __init__(self):
     self.CACHE_HOME = os.path.join(BaseDirectory.xdg_cache_home, "puding")
     # creating cache home if it doesn't exist
     if not os.path.isdir(self.CACHE_HOME):
         os.makedirs(self.CACHE_HOME)
     self.CONFIG_HOME = BaseDirectory.save_config_path("puding")
     self.CONFIG_FILE = os.path.join(self.CONFIG_HOME, "settings.json")
     self.DATA_HOME = BaseDirectory.save_data_path("puding")
     self.DATA_PATH = map(self.append_app_name, BaseDirectory.xdg_data_dirs)
     self.DEV_HOME = os.path.abspath(os.path.dirname(__file__))
开发者ID:dhirajkhatiwada1,项目名称:uludag,代码行数:10,代码来源:resources.py

示例5: _cache_database

def _cache_database():
    global exts, globs, literals, magic, aliases, inheritance, _cache_uptodate

    _cache_uptodate = True

    exts = {}       # Maps extensions to types
    globs = []      # List of (glob, type) pairs
    literals = {}   # Maps literal names to types
    aliases = {}    # Maps alias Mime types to canonical names
    inheritance = defaultdict(set) # Maps to sets of parent mime types.
    magic = MagicDB()

    def _import_glob_file(path):
        """Loads name matching information from a MIME directory."""
        with open(path) as f:
          for line in f:
            if line.startswith('#'): continue
            line = line[:-1]

            type_name, pattern = line.split(':', 1)
            mtype = lookup(type_name)

            if pattern.startswith('*.'):
                rest = pattern[2:]
                if not ('*' in rest or '[' in rest or '?' in rest):
                    if rest not in exts:
                        exts[rest] = mtype
                    continue
            if '*' in pattern or '[' in pattern or '?' in pattern:
                globs.append((pattern, mtype))
            else:
                literals[pattern] = mtype

    for path in BaseDirectory.load_data_paths(os.path.join('mime', 'globs')):
        _import_glob_file(path)
    for path in BaseDirectory.load_data_paths(os.path.join('mime', 'magic')):
        magic.mergeFile(path)

    # Sort globs by length
    globs.sort(key=lambda x: len(x[0]) )
    
    # Load aliases
    for path in BaseDirectory.load_data_paths(os.path.join('mime', 'aliases')):
        with open(path, 'r') as f:
            for line in f:
                alias, canonical = line.strip().split(None, 1)
                aliases[alias] = canonical
    
    # Load subclasses
    for path in BaseDirectory.load_data_paths(os.path.join('mime', 'subclasses')):
        with open(path, 'r') as f:
            for line in f:
                sub, parent = line.strip().split(None, 1)
                inheritance[sub].add(parent)
开发者ID:SugarApple,项目名称:RPiTC,代码行数:54,代码来源:Mime.py

示例6: __init__

 def __init__(self, debug=False):
     homedir = os.path.expanduser('~')
     self._conf_dir_name = BaseDirectory.save_config_path('actracker')
     self._log_dir_name = BaseDirectory.save_data_path('actracker')
     self._conf_fname = os.path.join(self._conf_dir_name, 'conf.json')
     self._load_conf()
     self._load_log()
     self._last_application = ('', '')
     self.activity_counter = {}
     self._current_day = datetime.now().day
     self.debug = debug
开发者ID:FedericoCeratto,项目名称:actracker,代码行数:11,代码来源:actmon.py

示例7: parse_opts

def parse_opts():
    '''
    This method parses the commandline options to next, if any, and it parses
    the configuration file
    '''
    t = TUI()

    parser = OptionParser(usage=constants.USAGE)
    parser.add_option(u'-c', u'--conf', nargs=1, dest=u'new_path', 
            help=u'NEW_PATH specifies a different configuration file')
    parser.add_option(u'-r', u'--random', action="store_const", dest="func", const=t.do_random, help=u'Start an ep for a random show')
    parser.add_option(u'-l', u'--list', action="store_const", dest="func", const=t.do_list, help=u'List all your shows')
    parser.add_option(u'-n', u'--new', action="store_const", dest="func", const=t.do_new, help=u'List shows for which there are new eps on your system')
    parser.add_option(u'-u', u'--update', action="store_const", dest="func", const=t.do_update, help=u'Connect to the TVRage database and update your show information')
    parser.add_option(u'-a', u'--add', action="store_const", dest="func", const=t.do_add_show, help=u'Add a show to the database')
    parser.add_option(u'--add_location', action="store_const", dest="func", const=t.do_add_show_location, help=u'Add a location for a show to the database')
    parser.add_option(u'--change', action="store_const", dest="func", const=t.do_change_show, help=u'Change the current season and ep for a show')
    parser.add_option(u'--scan', action="store_const", dest="func", const=t.do_scan, help=u'Scan your series path for shows')
    (options, args) = parser.parse_args()

    # Load a default config
    config = ConfigParser.SafeConfigParser()
    config.add_section(u'general')
    config.set(u'general', constants.ConfKeys.PLAYER_CMD, u'mplayer')
    config.set(u'general', constants.ConfKeys.SHOW_PATH, u'~/downloads/series')

    db_path = BaseDirectory.save_data_path('next')
    config.set(u'general', constants.ConfKeys.DB_PATH, db_path)

    # Load the config override
    if options.new_path:
        path = options.new_path
        if not (os.path.exists(path) and os.access(path, os.F_OK) and
                os.access(path, os.W_OK)):
            print u'No configfile found in "{0}", generating default configfile. Please modify, then start next again!'.format(path)
            gen_example(path)
            sys.exit(-1)
    else:
        path = BaseDirectory.load_first_config('next', 'next.conf')

    if path:
        config.read(path)

    result = dict(config.items(u'general'))

    for (k, v) in result.items(): # make sure bools are parsed correct
        if 'false' == v.lower() or 'no' == v.lower() or '0' == v:
            result[k] = False
        if 'true' == v.lower() or 'yes' == v.lower() or '1' == v:
            result[k] = True

    t.conf = result

    return options, result, args
开发者ID:Sakartu,项目名称:next,代码行数:54,代码来源:config.py

示例8: test_runtime_dir_notset

 def test_runtime_dir_notset(self):
     environ.pop('XDG_RUNTIME_DIR', None)
     self.assertRaises(KeyError, BaseDirectory.get_runtime_dir, strict=True)
     fallback = BaseDirectory.get_runtime_dir(strict=False)
     assert fallback.startswith('/tmp/'), fallback
     assert os.path.isdir(fallback), fallback
     mode = stat.S_IMODE(os.stat(fallback).st_mode)
     self.assertEqual(mode, stat.S_IRUSR|stat.S_IWUSR|stat.S_IXUSR)
     
     # Calling it again should return the same directory.
     fallback2 = BaseDirectory.get_runtime_dir(strict=False)
     self.assertEqual(fallback, fallback2)
     mode = stat.S_IMODE(os.stat(fallback2).st_mode)
     self.assertEqual(mode, stat.S_IRUSR|stat.S_IWUSR|stat.S_IXUSR)
开发者ID:0312birdzhang,项目名称:pyxdg,代码行数:14,代码来源:test-basedirectory.py

示例9: _get_status_filename

def _get_status_filename():
    """
    Get the status filename.
    Filename generated from xdg module, in $XDG_RUNTIME_DIR or in /tmp (in this order).
    """
    logger = logging.getLogger("_get_status_filename")
    status_basename = "chrandr.state"
    runtime_dir = None
    try:
        from xdg import BaseDirectory

        runtime_dir = BaseDirectory.get_runtime_dir()
    except ImportError:
        logger.info("xdg module not found")
        runtime_dir = os.getenv("XDG_RUNTIME_DIR")
    except KeyError:
        pass
    if runtime_dir is None:
        logger.debug("No environment variable XDG_RUNTIME_DIR")
        # no runtime dir, use /tmp
        import tempfile

        runtime_dir = tempfile.gettempdir()
        status_basename = "chrandr." + str(os.getuid()) + ".state"
    filename = os.path.join(runtime_dir, status_basename)
    logger.debug("Status filename: %s", filename)
    return filename
开发者ID:riskou,项目名称:chrandr,代码行数:27,代码来源:config.py

示例10: get_auth

def get_auth():
    def check_auth(auth):
        return requests.head(full_repo_url, auth=auth).status_code != httplib.UNAUTHORIZED

    # config file init
    config_file = os.path.join(BaseDirectory.save_config_path("malucrawl_reportificate"), "settings.ini")
    config = configparser.SafeConfigParser()
    config.read(config_file)

    if not config.has_section('auth'):
        config.add_section('auth')

    try:
        username = config.get('auth', 'username')
    except configparser.NoOptionError:
        username = raw_input("Username: ")

    password = keyring.get_password(github_url, username)
    if password is None:
        password = getpass.getpass()

    while not check_auth((username, password)):
        print "Authorization Failed"
        username = raw_input("Username: ")
        password = getpass.getpass()

    keyring.set_password(github_url, username, password)
    config.set('auth', 'username', username)
    config.write(open(config_file, 'w'))

    return (username, password)
开发者ID:graingert,项目名称:reportificate,代码行数:31,代码来源:reportificate.py

示例11: main

def main():
    cache_directory = BaseDirectory.save_cache_path('ob_xdg_apps')
    xml_file = os.path.join(cache_directory, 'menu.xml')

    appdirs = (os.path.join(datadir, 'applications') for datadir in
               BaseDirectory.xdg_data_dirs)

    if os.path.isfile(xml_file):
        updated = False
        for appdir in appdirs:
            if os.path.isdir(appdir):
                if os.stat(appdir).st_ctime > os.stat(xml_file).st_ctime:
                    updated = True
                    break

        if not updated:
            with open(xml_file) as f:
                print f.read()
            return

    icon_theme = gtk.icon_theme_get_default()

    menu = etree.Element('openbox_pipe_menu')
    menu_accumulator = MenuAccumulator()
    for desktop_entry in get_desktop_entries():
        menu_accumulator.add_entry(desktop_entry)
    menu_accumulator.finalize()

    categories = sorted(menu_accumulator.structure.keys())

    for category in categories:
        submenu_id = '{}-submenu'.format(category)
        submenu = etree.SubElement(menu, 'menu',
                                   {'id': submenu_id, 'label': category})

        for desktop_entry in menu_accumulator.structure[category]:
            name = desktop_entry.getName()
            item_attributes = {'label': name.decode('utf-8')}
            entry_icon = desktop_entry.getIcon()
            if os.path.isfile(entry_icon):
                item_attributes['icon'] = entry_icon
            else:
                icon_name = os.path.splitext(entry_icon)[0]
                icon_info = icon_theme.lookup_icon(icon_name, 48, 0)
                if icon_info is not None:
                    item_attributes['icon'] = icon_info.get_filename()
            item = etree.SubElement(submenu, 'item', item_attributes)
            action = etree.SubElement(item, 'action', {'name': 'Execute'})
            command = etree.SubElement(action, 'command')
            command.text = desktop_entry.getExec()

            if desktop_entry.getStartupNotify():
                startup_notify = etree.SubElement(action, 'startupnotify')
                enabled = etree.SubElement(startup_notify, 'enabled')
                enabled.text = 'yes'

    xml = etree.tostring(menu, pretty_print=True)
    with open(xml_file, 'w') as f:
        f.write(xml)
    print xml
开发者ID:duganchen,项目名称:ob_xdg_app_pipe,代码行数:60,代码来源:ob_xdg_apps.py

示例12: load_config

def load_config():
    resource_name = 'yt-bulk-py'

    if not bd.load_first_config(resource_name):
        sys.stderr.write('Creating config directory: ' + bd.save_config_path(resource_name))

    conf_dir = bd.load_first_config(resource_name)
    conf_file = os.path.join(conf_dir, 'config')

    conf_skel = """# Configuration file for yt-bulk-py

# Account information for the user doing the uploading.
[user]
email = [email protected]
password = secret
"""

    if not os.path.isfile(conf_file):
        with open(conf_file, 'w+b') as f:
            f.write(conf_skel)

    config = ConfigParser.ConfigParser()
    config.read(conf_file)

    if not 'user' in config.sections():
        sys.stderr.write('Error: No [user] section in config file.')
        exit(1)

    if not 'email' in config.options('user') and 'password' in config.options('user'):
        sys.stderr.write('Error: Missing "email" or "password" options in config file.')
        exit(1)
    return (config.get('user', 'email'), config.get('user', 'password'))
开发者ID:ahebrank,项目名称:yt-bulk-py,代码行数:32,代码来源:yt-bulk-py.py

示例13: on_checkautostart_toggled

	def on_checkautostart_toggled(self, widget):
		KUPFER_DESKTOP = "kupfer.desktop"
		AUTOSTART_KEY = "X-GNOME-Autostart-enabled"
		autostart_dir = base.save_config_path("autostart")
		autostart_file = os.path.join(autostart_dir, KUPFER_DESKTOP)
		if not os.path.exists(autostart_file):
			desktop_files = list(base.load_data_paths("applications",
				KUPFER_DESKTOP))
			if not desktop_files:
				self.output_error("Installed kupfer desktop file not found!")
				return
			desktop_file_path = desktop_files[0]
			# Read installed file and modify it
			dfile = desktop.DesktopEntry(desktop_file_path)
			executable = dfile.getExec()
			## append no-splash
			if "--no-splash" not in executable:
				executable += " --no-splash"
			dfile.set("Exec", executable)
		else:
			dfile = desktop.DesktopEntry(autostart_file)
		activestr = str(bool(widget.get_active())).lower()
		self.output_debug("Setting autostart to", activestr)
		dfile.set(AUTOSTART_KEY, activestr)
		## remove the format specifiers
		executable = dfile.getExec().replace("%F", "")
		dfile.set("Exec", executable)
		dfile.write(filename=autostart_file)
开发者ID:sagivmalihi,项目名称:kupfer,代码行数:28,代码来源:preferences.py

示例14: __init__

    def __init__(self):
        config_dir = xdg.save_config_path('hobo')
        data_dir = xdg.save_data_path('hobo')
        self.images_dir = os.path.join(data_dir, 'images')

        if not os.path.isdir(self.images_dir):
            os.mkdir(self.images_dir)

        self.template_file = os.path.join(self.images_dir, 'hobo.templates')
        touch(self.template_file)

        self.db = Db(os.path.join(data_dir, 'hobo.db'))

        config_file = os.path.join(config_dir, 'hobo.ini')
        self._cfg = ConfigParser()
        self._cfg.read(config_file)

        self.bridge_device = self.get('config', 'bridge_device') or 'hob0'
        self.base_mem = self.get('config', 'base_mem') or '1024'
        self.base_cpu = self.get('config', 'base_cpu') or '1'

        # compression analysis:
        #  -1 256M
        #  -9 213M
        #  --best 223M
        # might as well use -1
        # libvirt docs recommend:
        #   --best --block-size=16777216
        # but it's sloooow
        self.compress_flags = self.get('config', 'compress_flags') or '-1 -T0 --block-size=16777216'
开发者ID:mikewaters,项目名称:hobo,代码行数:30,代码来源:util.py

示例15: load_credentials

def load_credentials():
    p = xdgb.load_first_config('prisma', 'credentials')
    if p is None:
        exit('Please save your card number and password (each on its own line) in {}/credentials'
              .format(xdgb.save_config_path('prisma')))
    with open(p, 'r') as f:
        t = f.read().split()
        return (t[0], t[1])
开发者ID:kirelagin,项目名称:prismasok,代码行数:8,代码来源:util.py


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