本文整理汇总了Python中six.moves.configparser.ConfigParser类的典型用法代码示例。如果您正苦于以下问题:Python ConfigParser类的具体用法?Python ConfigParser怎么用?Python ConfigParser使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ConfigParser类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setUp
def setUp(self):
rid = '60754-10'
config = ConfigParser()
p = '/Users/ross/Sandbox/pychron_validation_data.cfg'
config.read(p)
signals = [list(map(float, x.split(','))) for x in [config.get('Signals-{}'.format(rid), k)
for k in ['ar40', 'ar39', 'ar38', 'ar37', 'ar36']]]
blanks = [list(map(float, x.split(','))) for x in [config.get('Blanks-{}'.format(rid), k)
for k in ['ar40', 'ar39', 'ar38', 'ar37', 'ar36']]]
irradinfo = [list(map(float, x.split(','))) for x in [config.get('irrad-{}'.format(rid), k) for k in ['k4039', 'k3839', 'ca3937', 'ca3837', 'ca3637', 'cl3638']]]
j = config.get('irrad-{}'.format(rid), 'j')
j = [float(x) for x in j.split(',')]
baselines = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]
backgrounds = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]
ar37df = config.getfloat('irrad-{}'.format(rid), 'ar37df')
t = math.log(ar37df) / (constants.lambda_37.nominal_value * 365.25)
irradinfo.append(t)
# load results
r = 'results-{}'.format(rid)
self.age = config.getfloat(r, 'age')
self.rad4039 = config.getfloat(r, 'rad4039')
self.ca37k39 = config.getfloat(r, 'ca37k39')
self.age_dict = calculate_arar_age(signals, baselines, blanks, backgrounds, j, irradinfo,
)
示例2: load_config
def load_config(config_file=_CONFIG_FILE):
cfg_parser = ConfigParser()
if not os.path.isfile(config_file):
raise Exception(
'configuration file not found: {0}'.format(config_file))
cfg_parser.read(config_file)
_cfg.load_config(cfg_parser)
示例3: handleSection
def handleSection(self, section, items):
locales = items['locales']
if locales == 'all':
inipath = '/'.join((
items['repo'], items['mozilla'],
'raw-file', 'default',
items['l10n.ini']
))
ini = ConfigParser()
ini.readfp(urlopen(inipath))
allpath = urljoin(
urljoin(inipath, ini.get('general', 'depth')),
ini.get('general', 'all'))
locales = urlopen(allpath).read()
locales = locales.split()
obs = (Active.objects
.filter(run__tree__code=section)
.exclude(run__locale__code__in=locales)
.order_by('run__locale__code'))
obslocs = ' '.join(obs.values_list('run__locale__code', flat=True))
if not obslocs:
self.stdout.write(' OK\n')
return
s = input('Remove %s? [Y/n] ' % obslocs)
if s.lower() == 'y' or s == '':
obs.delete()
示例4: _load_object_post_as_copy_conf
def _load_object_post_as_copy_conf(self, conf):
if ('object_post_as_copy' in conf or '__file__' not in conf):
# Option is explicitly set in middleware conf. In that case,
# we assume operator knows what he's doing.
# This takes preference over the one set in proxy app
return
cp = ConfigParser()
if os.path.isdir(conf['__file__']):
read_conf_dir(cp, conf['__file__'])
else:
cp.read(conf['__file__'])
try:
pipe = cp.get("pipeline:main", "pipeline")
except (NoSectionError, NoOptionError):
return
proxy_name = pipe.rsplit(None, 1)[-1]
proxy_section = "app:" + proxy_name
try:
conf['object_post_as_copy'] = cp.get(proxy_section,
'object_post_as_copy')
except (NoSectionError, NoOptionError):
pass
示例5: reload_constraints
def reload_constraints():
"""
Parse SWIFT_CONF_FILE and reset module level global contraint attrs,
populating OVERRIDE_CONSTRAINTS AND EFFECTIVE_CONSTRAINTS along the way.
"""
global SWIFT_CONSTRAINTS_LOADED, OVERRIDE_CONSTRAINTS
SWIFT_CONSTRAINTS_LOADED = False
OVERRIDE_CONSTRAINTS = {}
constraints_conf = ConfigParser()
if constraints_conf.read(utils.SWIFT_CONF_FILE):
SWIFT_CONSTRAINTS_LOADED = True
for name in DEFAULT_CONSTRAINTS:
try:
value = constraints_conf.get('swift-constraints', name)
except NoOptionError:
pass
except NoSectionError:
# We are never going to find the section for another option
break
else:
try:
value = int(value)
except ValueError:
value = utils.list_from_csv(value)
OVERRIDE_CONSTRAINTS[name] = value
for name, default in DEFAULT_CONSTRAINTS.items():
value = OVERRIDE_CONSTRAINTS.get(name, default)
EFFECTIVE_CONSTRAINTS[name] = value
# "globals" in this context is module level globals, always.
globals()[name.upper()] = value
示例6: read_mcf
def read_mcf(mcf):
"""returns dict of ConfigParser object"""
mcf_list = []
def makelist(mcf2):
"""recursive function for MCF by reference inclusion"""
c = ConfigParser()
LOGGER.debug('reading {}'.format(mcf2))
with codecs.open(mcf2, encoding='utf-8') as fh:
c.readfp(fh)
mcf_dict = c.__dict__['_sections']
for section in mcf_dict.keys():
if 'base_mcf' in mcf_dict[section]:
base_mcf_path = get_abspath(mcf,
mcf_dict[section]['base_mcf'])
makelist(base_mcf_path)
mcf_list.append(mcf2)
else: # leaf
mcf_list.append(mcf2)
makelist(mcf)
c = ConfigParser()
for mcf_file in mcf_list:
LOGGER.debug('reading {}'.format(mcf))
with codecs.open(mcf_file, encoding='utf-8') as fh:
c.readfp(fh)
mcf_dict = c.__dict__['_sections']
return mcf_dict
示例7: restore_rois
def restore_rois(self, roifile):
"""restore ROI setting from ROI.dat file"""
cp = ConfigParser()
cp.read(roifile)
rois = []
self.mcas[0].clear_rois()
prefix = self.mcas[0]._prefix
if prefix.endswith('.'):
prefix = prefix[:-1]
iroi = 0
for a in cp.options('rois'):
if a.lower().startswith('roi'):
name, dat = cp.get('rois', a).split('|')
lims = [int(i) for i in dat.split()]
lo, hi = lims[0], lims[1]
# print('ROI ', name, lo, hi)
roi = ROI(prefix=prefix, roi=iroi)
roi.LO = lo
roi.HI = hi
roi.NM = name.strip()
rois.append(roi)
iroi += 1
poll(0.050, 1.0)
self.mcas[0].set_rois(rois)
cal0 = self.mcas[0].get_calib()
for mca in self.mcas[1:]:
mca.set_rois(rois, calib=cal0)
示例8: _populate_config_from_old_location
def _populate_config_from_old_location(self, conf):
if ('rate_limit_after_segment' in conf or
'rate_limit_segments_per_sec' in conf or
'max_get_time' in conf or
'__file__' not in conf):
return
cp = ConfigParser()
if os.path.isdir(conf['__file__']):
read_conf_dir(cp, conf['__file__'])
else:
cp.read(conf['__file__'])
try:
pipe = cp.get("pipeline:main", "pipeline")
except (NoSectionError, NoOptionError):
return
proxy_name = pipe.rsplit(None, 1)[-1]
proxy_section = "app:" + proxy_name
for setting in ('rate_limit_after_segment',
'rate_limit_segments_per_sec',
'max_get_time'):
try:
conf[setting] = cp.get(proxy_section, setting)
except (NoSectionError, NoOptionError):
pass
示例9: reader
def reader(filename=None):
if filename is None:
filename = ini_file
cfg = ConfigParser()
log.debug("Reading configuration from {} ...".format(ini_file))
cfg.read(filename)
return cfg
示例10: get_config
def get_config(options):
S3CFG = os.getenv("S3CFG", None)
if options.config:
# Command-line overrides everything
cfg = options.config
elif S3CFG is not None:
# Environment variable overrides defaults
cfg = S3CFG
else:
# New default
new_default = os.path.expanduser("~/.pegasus/s3cfg")
if os.path.isfile(new_default):
cfg = new_default
else:
# If the new default doesn't exist, try the old default
cfg = os.path.expanduser("~/.s3cfg")
if not os.path.isfile(cfg):
raise Exception("Config file not found")
debug("Found config file: %s" % cfg)
# Make sure nobody else can read the file
mode = os.stat(cfg).st_mode
if mode & (stat.S_IRWXG | stat.S_IRWXO):
raise Exception("Permissions of config file %s are too liberal" % cfg)
config = ConfigParser(DEFAULT_CONFIG)
config.read(cfg)
return config
示例11: get_stackstorm_version
def get_stackstorm_version():
"""
Return StackStorm version including git commit revision if running a dev release and a file
with package metadata which includes git revision is available.
:rtype: ``str``
"""
if 'dev' in __version__:
version = __version__
if not os.path.isfile(PACKAGE_METADATA_FILE_PATH):
return version
config = ConfigParser()
try:
config.read(PACKAGE_METADATA_FILE_PATH)
except Exception:
return version
try:
git_revision = config.get('server', 'git_sha')
except Exception:
return version
version = '%s (%s)' % (version, git_revision)
else:
version = __version__
return version
示例12: build_cli_examples
def build_cli_examples(_):
logger = logging.getLogger('cli-examples')
clidir = os.path.join(SPHINX_DIR, 'cli')
exini = os.path.join(clidir, 'examples.ini')
exdir = os.path.join(clidir, 'examples')
if not os.path.isdir(exdir):
os.makedirs(exdir)
config = ConfigParser()
config.read(exini)
rsts = []
for sect in config.sections():
rst, cmd = _build_cli_example(config, sect, exdir, logger)
if cmd:
logger.info('[cli] running example {0!r}'.format(sect))
logger.debug('[cli] $ {0}'.format(cmd))
subprocess.check_call(cmd, shell=True)
logger.debug('[cli] wrote {0}'.format(cmd.split()[-1]))
rsts.append(rst)
with open(os.path.join(exdir, 'examples.rst'), 'w') as f:
f.write('.. toctree::\n :glob:\n\n')
for rst in rsts:
f.write(' {0}\n'.format(rst[len(SPHINX_DIR):]))
示例13: pytest_collect_file
def pytest_collect_file(path, parent):
"""Handle running pylint on files discovered"""
config = parent.config
if not config.option.pylint:
return
if not path.ext == ".py":
return
# Find pylintrc to check ignore list
pylintrc_file = config.option.pylint_rcfile or PYLINTRC
# No pylintrc, therefore no ignores, so return the item.
if not pylintrc_file or not exists(pylintrc_file):
return PyLintItem(path, parent)
pylintrc = ConfigParser()
pylintrc.read(pylintrc_file)
ignore_list = []
try:
ignore_string = pylintrc.get('MASTER', 'ignore')
if len(ignore_string) > 0:
ignore_list = ignore_string.split(',')
except (NoSectionError, NoOptionError):
pass
rel_path = path.strpath.replace(parent.fspath.strpath, '', 1)[1:]
if not any(basename in rel_path for basename in ignore_list):
return PyLintItem(path, parent)
示例14: update_from
def update_from(self, file_path):
"""
Reads and loads user customised settings from the given file path.
:param file_path: Absolute path to user settings file conf.cfg.
"""
assert isinstance(file_path, six.text_type)
cfg_parser = ConfigParser(inline_comment_prefixes=("#",))
cfg_parser.read(file_path)
ptpycfg = cfg_parser["ptpython"]
converters = [ConfigParser.getboolean, ConfigParser.getint, ConfigParser.getfloat]
for key in ptpycfg:
converted = False
if key not in self.user_defined:
# Only settings provided in initial defaults dict can get
# customised with user defined values from conf.cfg file.
continue
for func in converters:
try:
value = func(cfg_parser, "ptpython", key)
except ValueError:
continue
else:
self.user_defined[key] = value
converted = True
break
if not converted:
self.user_defined[key] = ptpycfg.get(key, "")
示例15: _get_attach_points
def _get_attach_points(self, info, size_request):
has_attach_points_, attach_points = info.get_attach_points()
attach_x = attach_y = 0
if attach_points:
# this works only for Gtk < 3.14
# https://developer.gnome.org/gtk3/stable/GtkIconTheme.html
# #gtk-icon-info-get-attach-points
attach_x = float(attach_points[0].x) / size_request
attach_y = float(attach_points[0].y) / size_request
elif info.get_filename():
# try read from the .icon file
icon_filename = info.get_filename().replace('.svg', '.icon')
if icon_filename != info.get_filename() and \
os.path.exists(icon_filename):
try:
with open(icon_filename) as config_file:
cp = ConfigParser()
cp.readfp(config_file)
attach_points_str = cp.get('Icon Data', 'AttachPoints')
attach_points = attach_points_str.split(',')
attach_x = float(attach_points[0].strip()) / 1000
attach_y = float(attach_points[1].strip()) / 1000
except Exception as e:
logging.exception('Exception reading icon info: %s', e)
return attach_x, attach_y