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


Python ConfigParser.has_option方法代码示例

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


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

示例1: __init__

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import has_option [as 别名]
    def __init__(self):
        username = None
        api_key = None

        self.tags = []
        self.privacy = 'public restricted'

        config = ConfigParser()
        config.read('setup.cfg')

        section = 'saucelabs'
        if config.has_section(section):
            if config.has_option(section, 'username'):
                username = config.get(section, 'username')
            if config.has_option(section, 'api-key'):
                api_key = config.get(section, 'api-key')
            if config.has_option(section, 'tags'):
                self.tags = config.get(section, 'tags').split(',')
            if config.has_option(section, 'privacy'):
                self.privacy = config.get(section, 'privacy')

        self.username = os.getenv('SAUCELABS_USERNAME', username)
        self.api_key = os.getenv('SAUCELABS_API_KEY', api_key)

        if self.username is None:
            raise ValueError('Sauce Labs username must be set!')
        if self.api_key is None:
            raise ValueError('Sauce Labs API key must be set!')
开发者ID:birdsarah,项目名称:pytest-mozwebqa,代码行数:30,代码来源:saucelabs.py

示例2: get_ic_factor

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import has_option [as 别名]
    def get_ic_factor(self, det):
        # storing ic_factor in preferences causing issues
        # ic_factor stored in detectors.cfg

        p = os.path.join(paths.spectrometer_dir, 'detectors.cfg')
        # factors=None
        ic = 1, 1e-20
        if os.path.isfile(p):
            c = ConfigParser()
            c.read(p)
            det = det.lower()
            for si in c.sections():
                if si.lower() == det:
                    v, e = 1, 1e-20
                    if c.has_option(si, 'ic_factor'):
                        v = c.getfloat(si, 'ic_factor')
                    if c.has_option(si, 'ic_factor_err'):
                        e = c.getfloat(si, 'ic_factor_err')
                    ic = v, e
                    break
        else:
            self.debug('no detector file {}. cannot retrieve ic_factor'.format(p))

        r = ufloat(*ic)
        return r
开发者ID:UManPychron,项目名称:pychron,代码行数:27,代码来源:arar_age.py

示例3: verify_and_fix_config

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import has_option [as 别名]
def verify_and_fix_config(config_files, backend_name_format):
    override_conf_path = OVERRIDE_CINDER_CONF_FILE
    if len(config_files) > 2:
        print "Multiple config files detected. Please contact " \
              "[email protected]"
        sys.exit(1)
    if DEFAULT_CINDER_CONF_FILE in config_files:
        default_conf = ConfigParser()
        config_files.remove(DEFAULT_CINDER_CONF_FILE)
        default_conf.read(DEFAULT_CINDER_CONF_FILE)
        if default_conf.has_option('DEFAULT', 'enabled_backends'):
            print "Cinder configuration is correct. No changes needed."
            sys.exit(0)
        if len(config_files) == 1:
            # Override conf is present
            override_conf = ConfigParser()
            override_conf.read(config_files[0])
            override_conf_path = config_files[0]
            if override_conf.has_option('DEFAULT', 'enabled_backends'):
                print "Cinder configuration is correct. No changes needed."
                sys.exit(0)
            # Take union of both configs as new file needs to be created using
            # both the configs
            default_conf.read(config_files[0])
        else:
            override_conf = ConfigParser()
        _update_netapp_conf(default_conf, override_conf, backend_name_format)
        with open(override_conf_path, 'w') as fptr:
            override_conf.write(fptr)
    else:
        print "Default cinder conf not found. Please contact " \
              "[email protected]"
        sys.exit(1)
开发者ID:platform9,项目名称:support-locker,代码行数:35,代码来源:netapp_driver_upgrade_cinder_conf.py

示例4: _parse_config

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import has_option [as 别名]
    def _parse_config(self, config_file):
        """Read the specified configuration file.  
        
        Only use the configuration file's values to fill in settings not 
        already supplied to the constructor.
        """
        
        config = ConfigParser()
        config.read(config_file)

        if not config.has_section("jinx-client"):
            config.add_section("jinx-client")
        
        if not self.jinx_host:
            if not config.has_option("jinx-client", "jinx_host"):
                raise JinxConfigError("Missing 'jinx_host' parameter.")
            else:
                self.jinx_host = config.get('jinx-client', 'jinx_host')
        
        if not self.krb_keytab:
            if config.has_option("jinx-client", "keytab"):
                self.krb_keytab = config.get('jinx-client', 'keytab')
        
        if not self.cluster:
            if config.has_option("jinx-client", "cluster"):
                self.cluster = config.get('jinx-client', 'cluster')
开发者ID:lindenlab,项目名称:python-jinx-client,代码行数:28,代码来源:jinx_client.py

示例5: reconfigure

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import has_option [as 别名]
def reconfigure(cfg):
    if not os.path.exists(RCFG_FILE):
        return

    rcfg = ConfigParser()
    rcfg.read(RCFG_FILE)

    if rcfg.has_option("netcontrol", "credentials"):
        u, p = rcfg.get("netcontrol", "credentials").split(":")
        cfg.remove_option("users", "admin")
        if not p.startswith("{SHA}"):
            p = hashpw(p)
        cfg.set("users", u, p)

    if rcfg.has_option("netcontrol", "plugins"):
        for x in rcfg.get("netcontrol", "plugins").split():
            shell("netcontrol-pkg get " + x)

    if rcfg.has_option("netcontrol", "ssl"):
        c, k = rcfg.get("netcontrol", "ssl").split()
        cfg.set("ssl", "1")
        cfg.set("cert_key", k)
        cfg.set("cert_file", c)

    if rcfg.has_option("netcontrol", "port"):
        cfg.set("netcontrol", "bind_port", rcfg.get("netcontrol", "port"))

    if rcfg.has_option("netcontrol", "host"):
        cfg.set("netcontrol", "bind_host", rcfg.get("netcontrol", "host"))

    cfg.set("netcontrol", "firstrun", "no")
    cfg.save()
    os.unlink(RCFG_FILE)
开发者ID:GabrielDiniz,项目名称:FluxNetControl,代码行数:35,代码来源:deployed.py

示例6: downloadTweets

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import has_option [as 别名]
def downloadTweets(username, downloadNewerThanId=-1, downloadOlderThanId=999999999999999999):
	highestIdDownloaded = 0
	storedInfo = ConfigParser()
	storedInfo.optionxform = str  #Makes sure options preserve their case. Prolly breaks something down the line, but CASE!
	twitterInfoFilename = os.path.join(GlobalStore.scriptfolder, 'data', 'TwitterInfo.dat')
	if os.path.exists(twitterInfoFilename):
		storedInfo.read(twitterInfoFilename)
	if not storedInfo.has_section(username):
		storedInfo.add_section(username)
	if storedInfo.has_option(username, "highestIdDownloaded"):
		highestIdDownloaded = int(storedInfo.get(username, "highestIdDownloaded"))

	headers = {"Authorization": "{} {}".format(GlobalStore.commandhandler.apikeys.get('twitter', 'tokentype'), GlobalStore.commandhandler.apikeys.get('twitter', 'token'))}
	params = {"screen_name": username, "count": "200", "trim_user": "true", "exclude_replies": "true", "include_rts": "false"}
	if downloadNewerThanId > -1:
		params["since_id"] = downloadNewerThanId

	tweets = {}
	lowestIdFound = downloadOlderThanId
	newTweetsFound = True

	while newTweetsFound:
		params["max_id"] = lowestIdFound

		req = requests.get("https://api.twitter.com/1.1/statuses/user_timeline.json", headers=headers, params=params)
		apireply = json.loads(req.text)

		newTweetsFound = False
		for tweet in apireply:
			tweettext = tweet["text"].replace("\n", " ").encode(encoding="utf-8", errors="replace")
			#print "Tweet {}: {}".format(tweet["id"], tweettext)
			if tweet["id"] not in tweets:
				#print "  storing tweet"
				newTweetsFound = True
				tweets[tweet["id"]] = tweettext

				tweetId = int(tweet["id"])
				lowestIdFound = min(lowestIdFound, tweetId-1)
				highestIdDownloaded = max(highestIdDownloaded, tweetId)
			#else:
			#	print "  skipping duplicate tweet"

	#All tweets downloaded. Time to process them
	tweetfile = open(os.path.join(GlobalStore.scriptfolder, 'data', "tweets-{}.txt".format(username)), "a")
	#Sort the keys before saving, so we're writing from oldest to newest, so in the same order as the Twitter timeline (Not absolutely necessary, but it IS neat and tidy)
	for id in sorted(tweets.keys()):
		tweetfile.write(tweets[id] + "\n")
	tweetfile.close()

	storedInfo.set(username, "highestIdDownloaded", highestIdDownloaded)
	linecount = 0
	if storedInfo.has_option(username, "linecount"):
		linecount = storedInfo.getint(username, "linecount")
	linecount += len(tweets)
	storedInfo.set(username, "linecount", linecount)

	storedInfoFile = open(twitterInfoFilename, "w")
	storedInfo.write(storedInfoFile)
	storedInfoFile.close()
	return True
开发者ID:Heufneutje,项目名称:DideRobot,代码行数:62,代码来源:SharedFunctions.py

示例7: update

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import has_option [as 别名]
    def update(self):
        cp = ConfigParser()
        info_file = os.path.abspath('./activity/activity.info')
        cp.read(info_file)

        if cp.has_option('Activity', 'activity_version'):
            self.version = cp.get('Activity', 'activity_version')
        else:
            print 'Activity bundle has invalid version number'

        if cp.has_option('Activity', 'name'):
            self.activity_name = cp.get('Activity', 'name')
        else:
            print 'Activity bundle does not specify a name'

        if cp.has_option('Activity', 'bundle_id'):
            self.bundle_id = cp.get('Activity', 'bundle_id')
        else:
            print 'Activity bundle does not specify a bundle id'

        self.bundle_name = reduce(operator.add, self.activity_name.split())
        self.bundle_root_dir = self.bundle_name + '.activity'
        self.tar_root_dir = '%s-%s' % (self.bundle_name, self.version)

        if self.dist_name:
            self.xo_name = self.tar_name = self.dist_name
        else:
            self.xo_name = '%s-%s.xo' % (self.bundle_name, self.version)
            self.tar_name = '%s-%s.tar.bz2' % (self.bundle_name, self.version)
开发者ID:nvazquez,项目名称:Turtlebots,代码行数:31,代码来源:setup.py

示例8: __init__

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import has_option [as 别名]
class StoqdriversConfig:

    domain = 'stoqdrivers'

    def __init__(self, filename=None):
        """ filename is the name of the configuration file we're reading """

        self.filename = filename or (self.domain + '.conf')
        self.config = ConfigParser()
        self._load_config()

    def get_homepath(self):
        return os.path.join(os.getenv('HOME'), '.' + self.domain)

    def _open_config(self, path):
        filename = os.path.join(path, self.filename)
        if not os.path.exists(filename):
            return False
        self.config.read(filename)
        return True

    def _load_config(self):
        # Try to load configuration  from:
        # 1) $HOME/.$domain/$filename
        # 2) $PREFIX/etc/$domain/$filename
        # 3) /etc/$filename
        
        # This is a bit hackish:
        # $prefix / lib / $DOMAIN / lib / config.py
        #    -4      -3     -2      -1       0
        filename = os.path.abspath(__file__)
        stripped = filename.split(os.sep)[:-4]
        self.prefix = os.path.join(os.sep, *stripped)
        
        homepath = self.get_homepath()
        etcpath = os.path.join(self.prefix, 'etc', self.domain)
        globetcpath = os.path.join(os.sep, 'etc', self.domain)
        if not (self._open_config(homepath) or self._open_config(etcpath) or
                self._open_config(globetcpath)):
            raise ConfigError(_("Config file not found in: `%s', `%s' and "
                                "`%s'") % (homepath, etcpath, globetcpath))

    def has_section(self, section):
        return self.config.has_section(section)

    def has_option(self, name, section='General'):
        return self.config.has_option(section, name)
    
    def get_option(self, name, section='General'):
        if not self.config.has_section(section):
            raise  ConfigError(_("Invalid section: %s") % section)
        elif not self.config.has_option(section, name):
            raise ConfigError(_("%s does not have option: %s")
                              % (self.filename, name))
        return self.config.get(section, name)

    def set_option(self, name, section='General'):
        if not self.config.has_section(section):
            raise ConfigError(_("Invalid section: %s") % section)
        self.config.set(section, name)
开发者ID:Cywaithaka,项目名称:addons-cluster,代码行数:62,代码来源:configparser.py

示例9: read_config_file

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import has_option [as 别名]
    def read_config_file(self, config_file, section_name):
        # NOTE: ConfigParser's DEFAULT handling is kind of nuts
        config = ConfigParser()
        config.set('DEFAULT', 'here', os.getcwd())
        config.readfp(config_file)

        required_options = ['es.index_prefix', 'git.path']
        has_options = [
            config.has_option(section_name, option)
            for option in required_options
        ]

        if not all(has_options):
            raise ToolCommandError(
                'Missing some required options. Required options are: %s' % (
                    ', '.join(required_options)))

        working_dir = config.get(section_name, 'git.path')
        index_prefix = config.get(section_name, 'es.index_prefix')

        es_host = None
        if config.has_option(section_name, 'es.host'):
            es_host = config.get(section_name, 'es.host')

        return index_prefix, working_dir, es_host
开发者ID:fuckthe-code,项目名称:elastic-git,代码行数:27,代码来源:resync.py

示例10: SetupConfig

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import has_option [as 别名]
class SetupConfig(object):
    """Wrapper around the setup.cfg file if available.

    Mostly, this is here to cleanup setup.cfg from these settings:

    [egg_info]
    tag_build = dev
    tag_svn_revision = true
    """

    config_filename = SETUP_CONFIG_FILE

    def __init__(self):
        """Grab the configuration (overridable for test purposes)"""
        # If there is a setup.cfg in the package, parse it
        if not os.path.exists(self.config_filename):
            self.config = None
            return
        self.config = ConfigParser()
        self.config.read(self.config_filename)

    def has_bad_commands(self):
        if self.config is None:
            return False
        if not self.config.has_section('egg_info'):
            # bail out early as the main section is not there
            return False
        bad = False
        # Check 1.
        if self.config.has_option('egg_info', 'tag_build'):
            # Might still be empty.
            value = self.config.get('egg_info', 'tag_build')
            if value:
                logger.warn("%s has [egg_info] tag_build set to %r",
                            self.config_filename, value)
                bad = True
        # Check 2.
        if self.config.has_option('egg_info', 'tag_svn_revision'):
            if self.config.getboolean('egg_info', 'tag_svn_revision'):
                value = self.config.get('egg_info', 'tag_svn_revision')
                logger.warn("%s has [egg_info] tag_svn_revision set to %r",
                            self.config_filename, value)
                bad = True
        return bad

    def fix_config(self):
        if not self.has_bad_commands():
            logger.warn("Cannot fix already fine %s.", self.config_filename)
            return
        if self.config.has_option('egg_info', 'tag_build'):
            self.config.set('egg_info', 'tag_build', '')
        if self.config.has_option('egg_info', 'tag_svn_revision'):
            self.config.set('egg_info', 'tag_svn_revision', 'false')
        new_setup = open(self.config_filename, 'wb')
        try:
            self.config.write(new_setup)
        finally:
            new_setup.close()
        logger.info("New setup.cfg contents:")
        print ''.join(open(self.config_filename).readlines())
开发者ID:AlexisHuet,项目名称:zest.releaser,代码行数:62,代码来源:pypi.py

示例11: distro_from_setup_cfg

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import has_option [as 别名]
def distro_from_setup_cfg(filename):
    """
    Read a source checkout's distutils2 setup.cfg and create a Distribution for
    that checkout.

    filename can either be the path to the setup.cfg itself, or checkout
    directory containing the setup.cfg.
    """

    if os.path.isdir(filename):
        path = filename
        filename = os.path.join(filename, "setup.cfg")
        if not os.path.exists(filename):
            return None
    else:
        path, basename = os.path.split(filename)
        if basename != "setup.cfg":
            return None
    cfg = ConfigParser()
    cfg.read(filename)
    if not cfg.has_option("metadata", "name"):
        return None
    name = cfg.get("metadata", "name")
    if cfg.has_option("metadata", "version"):
        version = cfg.get("metadata", "version")
    else:
        version = None
    return pkg_resources.Distribution(
        location=path, project_name=name, version=version, precedence=pkg_resources.CHECKOUT_DIST
    )
开发者ID:ih64,项目名称:XRB-phot,代码行数:32,代码来源:easier_install.py

示例12: run_gui

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import has_option [as 别名]
def run_gui(input_start_page, end_page, strict):
    """ Batch cleans the pages in text/clean."""
    config = ConfigParser()
    config.read('book.cnf')
    if strict and \
        config.has_option('process', 'last_strict_page'):
        hold_page = config.getint('process', 'last_strict_page')
    elif not strict and \
        config.has_option('process', 'last_checked_page'):
        hold_page = config.getint('process', 'last_checked_page')
    else:
        hold_page = input_start_page
    print hold_page
    if input_start_page == 0:
        start_page = hold_page
    else:
        start_page = input_start_page
    lang = get_lang()
    lm = line_manager.LineManager(
        spell_checker.AspellSpellChecker(lang, './dict.{}.pws'.format(lang)),
        start_page,
        end_page
        )
    lm.load('text/clean')
    app = gui.main(lm, strict)
    lm.write_pages('text/clean', False)

    if strict and int(app.last_page) >= hold_page:
        config.set('process', 'last_strict_page', app.last_page)
    elif not strict and int(app.last_page) >= hold_page:
        config.set('process', 'last_checked_page', app.last_page)
    with open('book.cnf', 'wb') as f:
        config.write(f)
开发者ID:porcpine1967,项目名称:ocr-proofreader,代码行数:35,代码来源:ocr.py

示例13: _load_config

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import has_option [as 别名]
    def _load_config(self):
        config_file = os.path.expanduser(self.filename)
        self.log.debug("Enter _load_config(%s)" % config_file)

        config = ConfigParser()
        Configuration.changed_settings = False  # track changes

        config.read(config_file)
        if config.has_section('settings'):
            if config.has_option('settings', 'destination'):
                self.set_destination(config.get('settings', 'destination'))
            if config.has_option('settings', 'date_pattern'):
                self.date_pattern = config.get('settings', 'date_pattern', True)
            if config.has_option('settings', 'tempdir'):
                self.tempdir = os.path.abspath(os.path.expanduser(config.get('settings', 'tempdir')))
                if not os.path.exists(self.tempdir):
                    os.makedirs(self.tempdir)
            if config.has_option('settings', 'comment_pattern'):
                pattern = config.get('settings', 'comment_pattern', True)
                pattern = re.sub(r'%([a-z_][a-z_]+)', r'%(\1)s', pattern)
                self.comment_pattern = pattern
        self._read_feed_settings(config)
        self._add_stations(config)
        if Configuration.changed_settings:
            import shutil
            shutil.copy(config_file, config_file + '.bak')
            with open(config_file, 'w') as file:
                config.write(file)
            print("WARNING: Saved the old version of config file as '%s.bak' and updated configuration." % (config_file))
开发者ID:pimpmypixel,项目名称:capturadio,代码行数:31,代码来源:__init__.py

示例14: initConfig

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import has_option [as 别名]
    def initConfig(self):
        kate.debug("initConfig()")
        config_path = kate.pate.pluginDirectories[1] + "/%s/%s.conf" % (__name__, __name__)
        config_file = QFileInfo(config_path)

        if not config_file.exists():
            open(config_path, "w").close()

        config = ConfigParser()
        config.read(config_path)

        # init the DEFAULT options if they don't exist
        # the DEFAULT section is special and doesn't need to be created: if not config.has_section('DEFAULT'): config.add_section('DEFAULT')
        if not config.has_option("DEFAULT", "ignore"):
            config.set("DEFAULT", "ignore", "")
        if not config.has_option("DEFAULT", "filter"):
            config.set("DEFAULT", "filter", "*")
        if not config.has_option("DEFAULT", "finder_size"):
            config.set("DEFAULT", "finder_size", "400x450")
        if not config.has_option("DEFAULT", "config_size"):
            config.set("DEFAULT", "config_size", "300x350")
        if not config.has_option("DEFAULT", "search_type"):
            config.set("DEFAULT", "search_type", "word")

        # create the general section if it doesn't exist
        if not config.has_section("general"):
            config.add_section("general")

        # flush the config file
        config.write(open(config_path, "w"))

        # save the config object and config path as instance vars for use later
        self.config = config
        self.config_path = config_path
开发者ID:jorrel,项目名称:kate_directory_project,代码行数:36,代码来源:directory_project.py

示例15: parse_config

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import has_option [as 别名]
def parse_config(configs):
    """
    :type configs list
    :rtype: ConfigParser
    """
    conf = ConfigParser()

    all_configs = []
    while len(configs) > 0:
        all_configs += configs
        files = []
        for mask in configs:
            for f in glob.glob(mask):
                if os.path.isfile(f):
                    files.append(f)
        conf.read(files)
        configs = []
        if conf.has_option(DEFAULT_SECTION, "include"):
            configs = list(set(re.split(r'\s+', conf.get(DEFAULT_SECTION, "include"))) - set(all_configs))

    for section in conf.sections():
        for k, v in conf.items(DEFAULT_SECTION):
            if not conf.has_option(section, k):
                conf.set(section, k, v)
        for k, v in conf.items(section):
            v = re.sub(r'^\s*"|"\s*$', '', v) # remove quotes
            conf.set(section, k, v)

    conf.remove_section(DEFAULT_SECTION)

    if not conf.sections():
        usage("No sections found in config files " + ", ".join(all_configs))
    return conf
开发者ID:DmitryKoterov,项目名称:cachelrud,代码行数:35,代码来源:main.py


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