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


Python BaseDirectory.load_first_config方法代码示例

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


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

示例1: load_config

# 需要导入模块: from xdg import BaseDirectory [as 别名]
# 或者: from xdg.BaseDirectory import load_first_config [as 别名]
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,代码行数:34,代码来源:yt-bulk-py.py

示例2: __init__

# 需要导入模块: from xdg import BaseDirectory [as 别名]
# 或者: from xdg.BaseDirectory import load_first_config [as 别名]
    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,代码行数:27,代码来源:email.py

示例3: load_presets

# 需要导入模块: from xdg import BaseDirectory [as 别名]
# 或者: from xdg.BaseDirectory import load_first_config [as 别名]
    def load_presets(self, force=False):
        qjackctl_conf = xdgbase.load_first_config('rncbc.org/QjackCtl.conf')

        if qjackctl_conf:
            mtime = os.path.getmtime(qjackctl_conf)
            changed = mtime > getattr(self, '_conf_mtime', 0)

            if changed:
                log.debug("QjackCtl configuration file mtime changed "
                          "or previously unknown.")

            if force or changed or self.presets is None:
                log.debug("(Re-)Reading configuration.")
                (
                    preset_names,
                    self.settings,
                    self.default_preset
                ) = get_qjackctl_presets(qjackctl_conf, self.ignore_default)
                self.presets = {name: name.replace('_', ' ')
                                for name in preset_names}
                self.create_menu()

            self._conf_mtime = mtime
        elif self.presets or self.presets is None:
            log.warning("QjackCtl configuration file not found.")

            if __debug__ and self.presets:
                log.debug("Removing stored presets from memory.")

            self.presets = {}
            self.settings = {}
            self.default_preset = None
            self.create_menu()

        return True  # keep function scheduled
开发者ID:SpotlightKid,项目名称:jack-select,代码行数:37,代码来源:jackselect.py

示例4: load

# 需要导入模块: from xdg import BaseDirectory [as 别名]
# 或者: from xdg.BaseDirectory import load_first_config [as 别名]
    def load(self, *, config_fd: TextIO = None) -> None:
        config = ""
        if config_fd:
            config = config_fd.read()
        else:
            # Local configurations (per project) are supposed to be static.
            # 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)
开发者ID:mvo5,项目名称:snapcraft,代码行数:32,代码来源:config.py

示例5: write_ripper_config

# 需要导入模块: from xdg import BaseDirectory [as 别名]
# 或者: from xdg.BaseDirectory import load_first_config [as 别名]
def write_ripper_config():

    album_art_dict = {
        'album_art_dir': "~/Pictures/album_art",
        'embeded_art': True,
        'folder_art': False
    }

    encoders_dict = {}
    encoders_dict[0] = {
        'codec': 'flac',
        'output_dir': 'FLAC'
    }
    encoders_dict[1] = {
        'codec': 'mp3',
        'bitrate': 320,
        'output_dir': 'MP3_320'
    }

    config_out = {
        'album_art': album_art_dict,
        'encoders': encoders_dict,
        'output_prefix': "~/Music"
    }

    config_path = "%s/%s" % (xdg.load_first_config('trip'), RIPPER_CONFIG_FILE)

    write_config(config_out, config_path)
开发者ID:tmose1106,项目名称:misc_py_tools,代码行数:30,代码来源:json_config.py

示例6: read_convert_config

# 需要导入模块: from xdg import BaseDirectory [as 别名]
# 或者: from xdg.BaseDirectory import load_first_config [as 别名]
def read_convert_config():

    config_path = "%s/%s" % (xdg.load_first_config('trip'),
                             CONVERTER_CONFIG_FILE)
    config_dict = read_config(config_path)

    return config_dict
开发者ID:tmose1106,项目名称:misc_py_tools,代码行数:9,代码来源:json_config.py

示例7: load_credentials

# 需要导入模块: from xdg import BaseDirectory [as 别名]
# 或者: from xdg.BaseDirectory import load_first_config [as 别名]
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,代码行数:10,代码来源:util.py

示例8: _test

# 需要导入模块: from xdg import BaseDirectory [as 别名]
# 或者: from xdg.BaseDirectory import load_first_config [as 别名]
def _test():
    from xdg import BaseDirectory as xdgbase

    qjackctl_conf = xdgbase.load_first_config('rncbc.org/QjackCtl.conf')

    if qjackctl_conf:
        presets, _, default = get_qjackctl_presets(qjackctl_conf, True)
        for preset in sorted(presets):
            print(preset, "*" if preset == default else '')
开发者ID:SpotlightKid,项目名称:jack-select,代码行数:11,代码来源:qjackctlconf.py

示例9: parse_opts

# 需要导入模块: from xdg import BaseDirectory [as 别名]
# 或者: from xdg.BaseDirectory import load_first_config [as 别名]
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,代码行数:56,代码来源:config.py

示例10: get_video_directories

# 需要导入模块: from xdg import BaseDirectory [as 别名]
# 或者: from xdg.BaseDirectory import load_first_config [as 别名]
    def get_video_directories(self):
        """
        Returns all the directories configured to scan for video content.

        :returns: list of the directories
        :rtype: list
        """

        if 'video_dirs' in self._config:
            return self._config['video_dirs']

        # TODO: Move this code into a common function to make it easier
        # to load up other directories.

        # Check for the ~/.config/user-dirs.dirs file
        user_dirs = BaseDirectory.load_first_config('user-dirs.dirs')
        if not user_dirs:
            # Attempt to generate out the default user-dirs.dirs config
            try:
                subprocess.call(['xdg-user-dirs-update'])
            except OSError:
                return []

        # If the file still doesn't exist then something is very wrong
        # so just fail with an empty list.
        if not BaseDirectory.load_first_config('user-dirs.dirs'):
            return []

        # Load the user-dirs.dirs config file to get the configured videos
        # directory.
        for line in open(BaseDirectory.load_first_config('user-dirs.dirs')):
            line = line.strip()
            if line.startswith('#'):
                continue
            (name, value) = line.split('=', 1)
            if name == 'XDG_VIDEOS_DIR':
                return [os.path.expandvars(value[1:-1])]

        return []
开发者ID:damoxc,项目名称:encore,代码行数:41,代码来源:config.py

示例11: load_config

# 需要导入模块: from xdg import BaseDirectory [as 别名]
# 或者: from xdg.BaseDirectory import load_first_config [as 别名]
	def load_config(self):
		try:
			filename = 'jenkins-indicator.yml'
			path = BaseDirectory.load_first_config(filename) or os.path.join(os.path.dirname(__file__), filename)
			logging.debug("loading config from: %s" % (path,))
			with open(path) as f:
				self._config = yaml.load(f)
				return self._config
		except StandardError, e:
			import traceback
			traceback.print_exc()
			if hasattr(self, '_config'):
				return self._config
			raise
开发者ID:timbertson,项目名称:jenkins-indicator,代码行数:16,代码来源:main.py

示例12: test_load_first_config

# 需要导入模块: from xdg import BaseDirectory [as 别名]
# 或者: from xdg.BaseDirectory import load_first_config [as 别名]
 def test_load_first_config(self):
     tmpdir = tempfile.mkdtemp()
     tmpdir2 = tempfile.mkdtemp()
     tmpdir3 = tempfile.mkdtemp()
     path = os.path.join(tmpdir3, "wpokewefketnrhruit")
     os.mkdir(path)
     try:
         environ['XDG_CONFIG_HOME'] = tmpdir
         environ['XDG_CONFIG_DIRS'] = ":".join([tmpdir2, tmpdir3])
         reload(BaseDirectory)
         configdir = BaseDirectory.load_first_config("wpokewefketnrhruit")
         self.assertEqual(configdir, path)
     finally:
         shutil.rmtree(tmpdir)
         shutil.rmtree(tmpdir2)
         shutil.rmtree(tmpdir3)
开发者ID:0312birdzhang,项目名称:pyxdg,代码行数:18,代码来源:test-basedirectory.py

示例13: set_argparser_defaults_from_config

# 需要导入模块: from xdg import BaseDirectory [as 别名]
# 或者: from xdg.BaseDirectory import load_first_config [as 别名]
def set_argparser_defaults_from_config(argparser):
    """Set defaults for the argument parser by reading the configuration file, if it exists.

    The configuration file should reside in the XDG data directory for this application
    (see :const:`APP_SHORTNAME`) and have the filename defined by :const:`CONFIG_FILENAME`.

    This is a standard INI file.

    All command line parameters can be set in the config file in the ``[options]`` section by taking the "long"
    parameter name and replacing all dashes with underscores (e. g. ``api_token = foobar``).

    Command line parameters without a value can be included in the config file by simply specifying the
    long parameter name without a value; e. g. adding a line containing just ``force`` will make the program
    behave as if the ``--force`` option was specified.

    :param argparser: Argument parser object to populate with defaults obtained from the configuration file.
    :type argparser: argparse.ArgumentParser
    :return: Nothing
    :rtype: None
    :raises configparser.Error: Config file has invalid syntax.
    :raises OSError: Config file exists, but cannot be opened (or read from).
    """
    conf_dir = BaseDirectory.load_first_config(APP_SHORTNAME)
    if conf_dir is None:
        return

    path = os.path.join(conf_dir, CONFIG_FILENAME)
    if not os.path.isfile(path):
        return

    config = configparser.ConfigParser(
            allow_no_value=True,
            interpolation=None
    )
    config.read_dict({"options": {}})
    config.read(path)

    defaults = {}
    for key, value in config.items("options"):
        if value is None:
            # Specifying a parameter name without a value sets its value to True.
            value = True

        logging.debug("Setting default from config file: %s = %s", key, value)
        defaults[key] = value

    argparser.set_defaults(**defaults)
开发者ID:Tblue,项目名称:toggl-fetch,代码行数:49,代码来源:fetch.py

示例14: genre_format

# 需要导入模块: from xdg import BaseDirectory [as 别名]
# 或者: from xdg.BaseDirectory import load_first_config [as 别名]
def genre_format():

    genre_file = "%s/%s" % (xdg.load_first_config('trip'), 'genres')

    with open(genre_file) as config_file:
        
        genre_dictionary = {}
        index = 0
        
        for a_line in config_file:
            
            genre = a_line.rstrip('\n')
            
            genre_dictionary[str(index)] = genre

            index += 1

    return genre_dictionary
开发者ID:tmose1106,项目名称:misc_py_tools,代码行数:20,代码来源:genre.py

示例15: __init__

# 需要导入模块: from xdg import BaseDirectory [as 别名]
# 或者: from xdg.BaseDirectory import load_first_config [as 别名]
	def __init__ (self, screenlet_classobj, backend_type='caching', name='default'):
		object.__init__(self)
		# check type
		if not screenlet_classobj.__name__.endswith('Screenlet'):
			# TODO: also check for correct type (Screenlet-subclass)!!
			raise Exception("ScreenletSession.__init__ has to be called with a valid Screenlet-classobject as first argument!")
		# init props
		self.name 		= name
		self.screenlet 	= screenlet_classobj
		self.instances 	= []
		self.tempfile	= TMP_DIR + '/' + TMP_FILE
		# check sys.args for "--session"-argument and override name, if set
		self.__parse_commandline()
		# set session path (and create dir-tree if not existent)
		p = screenlet_classobj.__name__[:-9] + '/' + self.name + '/'
		self.path = BaseDirectory.load_first_config('screenlets/' + p)
		if self.path == None:
			self.path = BaseDirectory.save_config_path('screenlets/' + p)
		if self.path == None: self.path = os.path.join(screenlets.DIR_CONFIG,p)
		if self.path:
			if backend_type == 'caching':
				self.backend = backend.CachingBackend(path=self.path)
			elif backend_type == 'gconf':
				self.backend = backend.GconfBackend()	
		else:
			# no config-dir? use dummy-backend and note about problem
			self.backend = backend.ScreenletsBackend()
			print "Unable to init backend - settings will not be saved!"
		# WORKAROUND: connect to daemon (ideally the daemon should watch the 
		#             tmpfile for changes!!)


		# NOTE: daemon will be started by bus.get_object anyway!!!
		#check for daemon
		#proc = os.popen("""ps axo "%p,%a" | grep "python.*screenlets-daemon.py" | grep -v grep|cut -d',' -f1""").read()
	
		#procs = proc.split('\n')
		#if len(procs) <= 1:
		#	os.system('python -u ' + screenlets.INSTALL_PREFIX + '/share/screenlets-manager/screenlets-daemon.py &')
		#	print 'No Daemon, Launching Daemon'
		self.connect_daemon()
开发者ID:PabloCastellano,项目名称:screenlets,代码行数:43,代码来源:session.py


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