本文整理汇总了Python中six.moves.configparser.ConfigParser.has_option方法的典型用法代码示例。如果您正苦于以下问题:Python ConfigParser.has_option方法的具体用法?Python ConfigParser.has_option怎么用?Python ConfigParser.has_option使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.configparser.ConfigParser
的用法示例。
在下文中一共展示了ConfigParser.has_option方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_ic_factor
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.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, 0
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, 0
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
示例2: _generate_appdata
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import has_option [as 别名]
def _generate_appdata(self, prefix, activity_path):
info = ConfigParser()
info.read(os.path.join(activity_path, 'activity', 'activity.info'))
required_fields = ['metadata_license', 'license', 'name', 'icon',
'description']
for name in required_fields:
if not info.has_option('Activity', name):
print('[WARNING] Activity needs more metadata for AppStream '
'file')
print(' Without an AppStream file, the activity will NOT '
'show in software stores!')
print(' Please `pydoc sugar3.activity.bundlebuilder` for'
'more info')
return
# See https://www.freedesktop.org/software/appstream/docs/
root = ET.Element('component', type='desktop')
ET.SubElement(root, 'project_group').text = 'Sugar'
ET.SubElement(root, 'translation', type='gettext').text = \
self.config.bundle_id
ET.SubElement(root, 'id').text = \
self.config.bundle_id + '.activity.desktop'
desc = ET.fromstring('<description>{}</description>'.format(
info.get('Activity', 'description')))
root.append(desc)
copy_pairs = [('metadata_license', 'metadata_license'),
('license', 'project_license'),
('summary', 'summary'),
('name', 'name')]
for key, ename in copy_pairs:
ET.SubElement(root, ename).text = info.get('Activity', key)
if info.has_option('Activity', 'screenshots'):
screenshots = info.get('Activity', 'screenshots').split()
ss_root = ET.SubElement(root, 'screenshots')
for i, screenshot in enumerate(screenshots):
e = ET.SubElement(ss_root, 'screenshot')
if i == 0:
e.set('type', 'default')
ET.SubElement(e, 'image').text = screenshot
if info.has_option('Activity', 'url'):
ET.SubElement(root, 'url', type='homepage').text = \
info.get('Activity', 'url')
if info.has_option('Activity', 'repository_url'):
ET.SubElement(root, 'url', type='bugtracker').text = \
info.get('Activity', 'repository_url')
elif info.has_option('Activity', 'repository'):
ET.SubElement(root, 'url', type='bugtracker').text = \
info.get('Activity', 'repository')
path = os.path.join(prefix, 'share', 'metainfo',
self.config.bundle_id + '.appdata.xml')
if not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
tree = ET.ElementTree(root)
tree.write(path, encoding='UTF-8')
示例3: read_config_file
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import has_option [as 别名]
def read_config_file(cfgfile, options):
config = ConfigParser()
config.readfp(open(cfgfile))
if config.has_option('testflo', 'skip_dirs'):
skips = config.get('testflo', 'skip_dirs')
options.skip_dirs = [s.strip() for s in skips.split(',') if s.strip()]
if config.has_option('testflo', 'num_procs'):
options.num_procs = int(config.get('testflo', 'num_procs'))
示例4: load
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import has_option [as 别名]
def load(self):
schemes = [defaultScheme]
parser = ConfigParser()
parser.read(settings.DASHBOARD_CONF)
for option, default_value in defaultUIConfig.items():
if parser.has_option('ui', option):
try:
self.ui_config[option] = parser.getint('ui', option)
except ValueError:
self.ui_config[option] = parser.get('ui', option)
else:
self.ui_config[option] = default_value
if parser.has_option('ui', 'automatic_variants'):
self.ui_config['automatic_variants'] = parser.getboolean('ui', 'automatic_variants')
else:
self.ui_config['automatic_variants'] = True
self.ui_config['keyboard_shortcuts'] = defaultKeyboardShortcuts.copy()
if parser.has_section('keyboard-shortcuts'):
self.ui_config['keyboard_shortcuts'].update( parser.items('keyboard-shortcuts') )
for section in parser.sections():
if section in ('ui', 'keyboard-shortcuts'):
continue
scheme = parser.get(section, 'scheme')
fields = []
for match in fieldRegex.finditer(scheme):
field = match.group(1)
if parser.has_option(section, '%s.label' % field):
label = parser.get(section, '%s.label' % field)
else:
label = field
fields.append({
'name' : field,
'label' : label
})
schemes.append({
'name' : section,
'pattern' : scheme,
'fields' : fields,
})
self.schemes = schemes
示例5: sync
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import has_option [as 别名]
def sync():
# Add or replace the relevant properites from galaxy.ini
# into reports.ini
reports_config_file = "config/reports.ini"
if len(argv) > 1:
reports_config_file = argv[1]
universe_config_file = "config/galaxy.ini"
if len(argv) > 2:
universe_config_file = argv[2]
parser = ConfigParser()
parser.read(universe_config_file)
with open(reports_config_file, "r") as f:
reports_config_lines = f.readlines()
replaced_properties = set([])
with open(reports_config_file, "w") as f:
# Write all properties from reports config replacing as
# needed.
for reports_config_line in reports_config_lines:
(line, replaced_property) = get_synced_line(reports_config_line, parser)
if replaced_property:
replaced_properties.add(replaced_property)
f.write(line)
# If any properties appear in universe config and not in
# reports write these as well.
for replacement_property in REPLACE_PROPERTIES:
if parser.has_option(MAIN_SECTION, replacement_property) and \
not (replacement_property in replaced_properties):
f.write(get_universe_line(replacement_property, parser))
示例6: _parse_linfo
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import has_option [as 别名]
def _parse_linfo(self, linfo_file):
cp = ConfigParser()
try:
cp.readfp(linfo_file)
section = 'Activity'
if cp.has_option(section, 'name'):
self._name = cp.get(section, 'name')
if cp.has_option(section, 'summary'):
self._summary = cp.get(section, 'summary')
if cp.has_option(section, 'tags'):
tag_list = cp.get(section, 'tags').strip(';')
self._tags = [tag.strip() for tag in tag_list.split(';')]
except ParsingError as e:
logging.exception('Exception reading linfo file: %s', e)
示例7: _install_desktop_file
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import has_option [as 别名]
def _install_desktop_file(self, prefix, activity_path):
cp = ConfigParser()
section = 'Desktop Entry'
cp.add_section(section)
cp.optionxform = str # Allow CamelCase entries
# Get it from the activity.info for the non-translated version
info = ConfigParser()
info.read(os.path.join(activity_path, 'activity', 'activity.info'))
cp.set(section, 'Name', info.get('Activity', 'name'))
if info.has_option('Activity', 'summary'):
cp.set(section, 'Comment', info.get('Activity', 'summary'))
for path in sorted(glob(os.path.join(activity_path, 'locale',
'*', 'activity.linfo'))):
locale = path.split(os.path.sep)[-2]
info = ConfigParser()
info.read(path)
if info.has_option('Activity', 'name'):
cp.set(section, 'Name[{}]'.format(locale),
info.get('Activity', 'name'))
if info.has_option('Activity', 'summary'):
cp.set(section, 'Comment[{}]'.format(locale),
info.get('Activity', 'summary'))
cp.set(section, 'Terminal', 'false')
cp.set(section, 'Type', 'Application')
cp.set(section, 'Categories', 'Education;')
cp.set(section, 'Icon', os.path.join(
activity_path, 'activity', self.config.bundle.get_icon_filename()))
cp.set(section, 'Exec', self.config.bundle.get_command())
cp.set(section, 'Path', activity_path) # Path == CWD for running
name = '{}.activity.desktop'.format(self.config.bundle_id)
path = os.path.join(prefix, 'share', 'applications', name)
if not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
with open(path, 'w') as f:
cp.write(f)
示例8: getLayoutsFromManifest
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import has_option [as 别名]
def getLayoutsFromManifest(fp, _format, directory_name):
# support multiple sections with the same name in manifest.cfg
if six.PY2:
parser = ConfigParser(None, multidict)
parser.readfp(fp)
else:
data = fp.read()
if isinstance(data, six.binary_type):
data = data.decode()
parser = ConfigParser(dict_type=multidict, strict=False)
parser.read_string(data)
layouts = {}
for section in parser.sections():
if not section.startswith(_format.resourceType) or \
':variants' in section:
continue
# id is a combination of directory name + filename
if parser.has_option(section, 'file'):
filename = parser.get(section, 'file')
else:
filename = '' # this should not happen...
_id = directory_name + '/' + filename
if _id in layouts:
# because TTW resources are created first, we consider layouts
# with same id in a TTW to be taken before other resources
continue
data = {
'directory': directory_name
}
for key in _format.keys:
if parser.has_option(section, key):
data[key] = parser.get(section, key)
else:
data[key] = _format.defaults.get(key, None)
layouts[_id] = data
return layouts
示例9: test_ignore_extra_params
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import has_option [as 别名]
def test_ignore_extra_params(self):
name = self.make_empty_temp_file()
to_config_file(
name, "section.name", {"invalid_parameter": "empty", "port_queue_dt": 1.2}
)
self.assertTrue(os.path.isfile(name))
config = ConfigParser()
config.read(name)
self.assertTrue(config.has_section("section.name"))
self.assertSetEqual(_VALID_KEYS, set(config.options("section.name")))
self.assertEqual(1.2, config.getfloat("section.name", "port_queue_dt"))
self.assertFalse(config.has_option("section.name", "invalid_parameter"))
示例10: load_theme
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import has_option [as 别名]
def load_theme(struct, path, colors, default_colors):
theme = ConfigParser()
with open(path, 'r') as f:
theme.readfp(f)
for k, v in chain(theme.items('syntax'), theme.items('interface')):
if theme.has_option('syntax', k):
colors[k] = theme.get('syntax', k)
else:
colors[k] = theme.get('interface', k)
# Check against default theme to see if all values are defined
for k, v in iteritems(default_colors):
if k not in colors:
colors[k] = v
示例11: serve
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import has_option [as 别名]
def serve(args):
config = ConfigParser({'port': '8080', 'db': None})
config.read([CONFIG_FILE])
port = int(args.port or int(config.get('app', 'port')))
view_path = getattr(args, 'view_path', None)
controller_path = getattr(args, 'controller_path', None)
if args.cdn is None:
if config.has_option('app', 'cdn'):
cdn = config.getboolean('app', 'cdn')
else:
cdn = True
else:
cdn = args.cdn
server.serve(db=config.get('app', 'db'), port=port, verbose=args.verbose,
view_path=view_path, controller_path=controller_path, cdn=cdn)
示例12: parse_config_file
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import has_option [as 别名]
def parse_config_file(filename):
logger.debug("reading configuration file: %s", filename)
cp = ConfigParser()
with open(filename) as f:
cp.readfp(f, filename=filename)
if cp.has_option('include', 'files'):
for fn in glob(cp.get('include', 'files')):
cp.read(fn)
cp.redis = cp.get('sup_broadcast', 'redis')
cp.url = cp.get('sup_broadcast', 'supervisor_url')
try:
cp.ident = cp.get('supervisord', 'identifier')
except Error:
cp.ident = _url2name(cp.url)
cp.config_file = filename
return cp
示例13: parse
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import has_option [as 别名]
def parse(self):
"""
Parse the config and return a dict with the parsed values.
:rtype: ``dict``
"""
result = defaultdict(dict)
if not os.path.isfile(self.config_file_path):
# Config doesn't exist, return the default values
return CONFIG_DEFAULT_VALUES
config = ConfigParser()
with open(self.config_file_path, 'r') as fp:
config.readfp(fp)
for section, keys in six.iteritems(CONFIG_FILE_OPTIONS):
for key, options in six.iteritems(keys):
key_type = options['type']
key_default_value = options['default']
if config.has_option(section, key):
if key_type in ['str', 'string']:
get_func = config.get
elif key_type in ['int', 'integer']:
get_func = config.getint
elif key_type in ['float']:
get_func = config.getfloat
elif key_type in ['bool', 'boolean']:
get_func = config.getboolean
else:
msg = 'Invalid type "%s" for option "%s"' % (key_type, key)
raise ValueError(msg)
value = get_func(section, key)
result[section][key] = value
else:
result[section][key] = key_default_value
return dict(result)
示例14: _parse_info
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import has_option [as 别名]
def _parse_info(self, info_file):
cp = ConfigParser()
cp.readfp(info_file)
section = 'Library'
if cp.has_option(section, 'name'):
self._name = cp.get(section, 'name')
else:
raise MalformedBundleException(
'Content bundle %s does not specify a name' % self._path)
if cp.has_option(section, 'library_version'):
version = cp.get(section, 'library_version')
try:
NormalizedVersion(version)
except InvalidVersionError:
raise MalformedBundleException(
'Content bundle %s has invalid version number %s' %
(self._path, version))
self._library_version = version
if cp.has_option(section, 'locale'):
self._locale = cp.get(section, 'locale')
if cp.has_option(section, 'global_name'):
self._global_name = cp.get(section, 'global_name')
if cp.has_option(section, 'icon'):
self._icon = cp.get(section, 'icon')
# Compatibility with old content bundles
if self._global_name is not None \
and cp.has_option(section, 'bundle_class'):
self._global_name = cp.get(section, 'bundle_class')
if cp.has_option(section, 'activity_start'):
self._activity_start = cp.get(section, 'activity_start')
if self._global_name is None:
raise MalformedBundleException(
'Content bundle %s must specify global_name' % self._path)
示例15: process_mistral_config
# 需要导入模块: from six.moves.configparser import ConfigParser [as 别名]
# 或者: from six.moves.configparser.ConfigParser import has_option [as 别名]
def process_mistral_config(config_path):
"""
Remove sensitive data (credentials) from the Mistral config.
:param config_path: Full absolute path to the mistral config inside /tmp.
:type config_path: ``str``
"""
assert config_path.startswith('/tmp')
if not os.path.isfile(config_path):
return
config = ConfigParser()
config.read(config_path)
for section, options in MISTRAL_CONF_OPTIONS_TO_REMOVE.items():
for option in options:
if config.has_option(section, option):
config.set(section, option, REMOVED_VALUE_NAME)
with open(config_path, 'w') as fp:
config.write(fp)