本文整理汇总了Python中ConfigParser.ConfigParser.read_file方法的典型用法代码示例。如果您正苦于以下问题:Python ConfigParser.read_file方法的具体用法?Python ConfigParser.read_file怎么用?Python ConfigParser.read_file使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConfigParser.ConfigParser
的用法示例。
在下文中一共展示了ConfigParser.read_file方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_conf
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read_file [as 别名]
def load_conf(path=None, file=None):
"""Load configuration in global var CONF
:param path: The path to the configuration file
:param file: If provided read instead the file like object
"""
conf = ConfigParser()
if file:
try:
conf.read_file(file, path)
except AttributeError:
# read_file only exists in Python3
conf.readfp(file)
return conf
confpath = None
if not path:
try:
confpath = os.environ['DULWICH_SWIFT_CFG']
except KeyError:
raise Exception("You need to specify a configuration file")
else:
confpath = path
if not os.path.isfile(confpath):
raise Exception("Unable to read configuration file %s" % confpath)
conf.read(confpath)
return conf
示例2: get_config_param
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read_file [as 别名]
def get_config_param(param):
"""
Parse config file and find source dir in it
"""
curdir = os.curdir
if '__file__' in globals():
curdir = os.path.dirname(os.path.abspath(__file__))
config = None
for loc in curdir, os.curdir, os.path.expanduser('~'):
try:
with open(os.path.join(loc, 'precommit1c.ini')) as source:
if sys.version_info < (3, 0, 0):
from ConfigParser import ConfigParser # @NoMove @UnusedImport
else:
from configparser import ConfigParser
config = ConfigParser()
config.read_file(source)
break
except IOError:
pass
if config is not None and config.has_option('default', param):
value = config.get('default', param)
return value
return None
示例3: values_from_file
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read_file [as 别名]
def values_from_file(docopt_dict, config_option, settable, booleans, repeatable):
"""Parse config file and read settable values.
Can be overridden by both command line arguments and environment variables.
:raise DocoptcfgError: If `config_option` isn't found in docstring.
:raise DocoptcfgFileError: On any error while trying to read and parse config file.
:param dict docopt_dict: Dictionary from docopt with environment variable defaults merged in by docoptcfg().
:param str config_option: Config option long name with file path as its value.
:param iter settable: Option long names available to set by config file.
:param iter booleans: Option long names of boolean/flag types.
:param iter repeatable: Option long names of repeatable options.
:return: Settable values.
:rtype: dict
"""
section = docopt.DocoptExit.usage.split()[1]
settable = set(o for o in settable if o != config_option)
config = ConfigParser()
defaults = dict()
# Sanity checks.
if config_option not in docopt_dict:
raise DocoptcfgError
if docopt_dict[config_option] is None or not settable:
return defaults
# Read config file.
path = DocoptcfgFileError.FILE_PATH = docopt_dict[config_option]
try:
with open(path) as handle:
if hasattr(config, 'read_file'):
config.read_file(handle)
else:
getattr(config, 'readfp')(handle)
except Error as exc:
raise DocoptcfgFileError('Unable to parse config file.', str(exc))
except IOError as exc:
raise DocoptcfgFileError('Unable to read config file.', str(exc))
# Make sure section is in config file.
if not config.has_section(section):
raise DocoptcfgFileError('Section [{0}] not in config file.'.format(section))
# Parse config file.
for key in settable:
if config.has_option(section, key[2:]):
defaults[key] = get_opt(key, config, section, booleans, repeatable)
return defaults
示例4: get_config
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read_file [as 别名]
def get_config(cls, arguments):
config_file = arguments.config
if not os.path.isfile(config_file):
raise ConfigurationError('configuration file not found: %s' % config_file)
cls.logger.debug('using config file: %s' % config_file)
config_parser = ConfigParser()
with codecs.open(config_file, "r", "utf8") as config_fp:
if hasattr(config_parser, 'read_file'):
config_parser.read_file(config_fp)
else:
config_parser.readfp(config_fp)
return Configuration(arguments, config_parser)
示例5: ssid_password
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read_file [as 别名]
def ssid_password(source='/etc/NetworkConnections/system-connections', ext=''):
if isinstance(source, ConfigParser):
ssid = source.get('wifi', 'ssid') if source.has_option('wifi', 'ssid') else None
psk = source.get('wifi-security', 'psk') if source.has_option('wifi-security', 'psk') else None
return (ssid or os.path.basename(source), psk or '')
elif os.path.isdir(source):
return dict([ssid_password(meta['path']) for meta in find_files(source, ext=ext)])
elif os.path.isfile(source) or callable(getattr(source, 'read', None)):
config = ConfigParser()
if hasattr(source, 'read'):
config.read_file(source)
else:
config.read(source)
return ssid_password(config)
elif isinstance(source, basestring):
return ssid_password(StringIO(source))
示例6: from_file
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read_file [as 别名]
def from_file(self, in_file):
if not hasattr(in_file, 'read'):
in_file = open(in_file, 'r')
config_parser = ConfigParser()
try:
# Python 3
config_parser.read_file(in_file)
except AttributeError:
# Python 2
config_parser.readfp(in_file)
return ToxConfig(
envlist=list(map(str.strip, config_parser.get('tox', 'envlist').split(','))),
commands=config_parser.get('testenv', 'commands')
)
示例7: from_file
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read_file [as 别名]
def from_file(cls, in_file):
if not hasattr(in_file, 'read'):
in_file = open(in_file, 'r')
config_parser = ConfigParser()
try:
# Python 3
config_parser.read_file(in_file)
except AttributeError:
# Python 2
config_parser.readfp(in_file)
return ToxConfig(
envlist=cls._get_envlist_from_tox(in_file.name),
commands=config_parser.get('testenv', 'commands')
)
示例8: get_defined_stops
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read_file [as 别名]
def get_defined_stops():
app_root = path.split(sys.path[0])[0]
backend_root = path.join(app_root, 'backend')
cp = ConfigParser()
with open(path.join(backend_root, 'stops.ini'), 'r', encoding='cp65001') as config_file: # windows utf-8
if PY2:
cp.readfp(config_file)
else:
cp.read_file(config_file)
stops = []
for section_name in cp.sections():
stop_configuration = cp.items(section_name)
stop_data = {}
for key, value in stop_configuration:
if key in ('name', 'pane'):
stop_data[key] = value
else:
stop_data[key] = int(value)
stops.append(stop_data)
return stops
示例9: configure
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read_file [as 别名]
def configure(self):
defaults = {}
defaults["message"] = "UNCLASSIFIED"
defaults["fgcolor"] = "#FFFFFF"
defaults["bgcolor"] = "#007A33"
defaults["face"] = "liberation-sans"
defaults["size"] = "small"
defaults["weight"] = "bold"
defaults["show_top"] = True
defaults["show_bottom"] = True
defaults["hres"] = 0
defaults["vres"] = 0
defaults["sys_info"] = False
defaults["opacity"] = 0.75
defaults["esc"] = True
defaults["spanning"] = False
# Check if a configuration file was passed in from the command line
default_heading = DEFAULTSECT
conf_parser = ArgumentParser(
formatter_class=RawDescriptionHelpFormatter,
add_help=False)
conf_parser.add_argument("-c", "--config",
help="Specify the configuration file",
metavar="FILE")
conf_parser.add_argument("--heading",
help="Specify the config. section to use.",
default=default_heading)
options, args = conf_parser.parse_known_args()
config_file = None
if options.config:
config_file = os.path.abspath(options.config)
if not os.path.isfile(config_file):
print("ERROR: Specified configuration file does not exist.")
sys.exit(1)
else:
config_file = os.path.abspath(CONF_FILE)
if not os.path.isfile(config_file):
config_file = None
# In order to maintain backwards compatibility with the way the
# previous configuration file format, a dummy section may need
# to be added to the configuration file. If this is the case,
# a temporary file is used in order to avoid overwriting the
# user's configuration.
config = ConfigParser()
if config_file is not None:
fp = open(config_file, "r")
while True:
try:
if sys.hexversion >= 0x03000000:
config.read_file(fp, source=config_file)
else:
config.readfp(fp, config_file)
break
except MissingSectionHeaderError:
# Recreate the file, adding a default section.
fp.close()
fp = TemporaryFile()
with open(config_file) as original:
fp.write("[%s]\n" % default_heading + original.read())
fp.seek(0)
fp.close() # If this was a temporary file it will now be deleted.
# ConfigParser treats everything as strings and any quotation
# marks in a setting are explicitly added to the string.
# One way to fix this is to add everything to the defaults and
# then strip the quotation marks off of everything.
defaults.update(dict(config.items(options.heading)))
for key, val in defaults.items():
if config.has_option(options.heading, key):
defaults[key] = val.strip("\"'")
# TODO: This coercion section is hacky and should be fixed.
for key in ["show_top", "show_bottom", "sys_info", "esc", "spanning"]:
if config.has_option(options.heading, key):
defaults[key] = config.getboolean(options.heading, key)
for key in ["hres", "vres"]:
if config.has_option(options.heading, key):
defaults[key] = config.getint(options.heading, key)
for key in ["opacity"]:
if config.has_option(options.heading, key):
defaults[key] = config.getfloat(options.heading, key)
# Use the global config to set defaults for command line options
parser = ArgumentParser(parents=[conf_parser])
parser.add_argument("-m", "--message", default=defaults["message"],
help="Set the Classification message")
parser.add_argument("-f", "--fgcolor", default=defaults["fgcolor"],
help="Set the Foreground (text) color")
parser.add_argument("-b", "--bgcolor", default=defaults["bgcolor"],
help="Set the Background color")
parser.add_argument("-x", "--hres", default=defaults["hres"], type=int,
help="Set the Horizontal Screen Resolution")
parser.add_argument("-y", "--vres", default=defaults["vres"], type=int,
help="Set the Vertical Screen Resolution")
parser.add_argument("-o", "--opacity", default=defaults["opacity"],
type=float, dest="opacity",
help="Set the window opacity for composted window managers")
#.........这里部分代码省略.........
示例10: from_stream
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read_file [as 别名]
def from_stream(stream):
"""Retrieves AWS settings from a stream in INI format.
Example:
>>> from io import StringIO
>>> stream = StringIO('''
...
... [credentials]
... aws_access_key_id=KEY_ID
... aws_secret_access_key=SECRET
...
... [defaults]
... region=eu-west-1
...
... ''')
>>> settings = from_stream(stream)
>>> settings['aws_access_key_id'] == 'KEY_ID'
True
>>> settings['aws_secret_access_key'] == 'SECRET'
True
>>> settings['region'] == 'eu-west-1'
True
>>> stream = StringIO('''
...
... [credentials]
... aws_access_key_id=KEY_ID
... aws_secret_access_key=SECRET
...
... ''')
>>> settings = from_stream(stream)
>>> settings['aws_access_key_id'] == 'KEY_ID'
True
>>> settings['aws_secret_access_key'] == 'SECRET'
True
:param stream: of chars in INI format.
:type stream: stream.
:rtype: dict
..note:: some fields may be None.
"""
config = ConfigParser(allow_no_value=True)
if hasattr(config, 'read_file'):
config.read_file(stream)
else:
config.readfp(stream) # deprecated name
settings = {}
if config.has_section('credentials'):
settings.update({
'aws_access_key_id': config.get('credentials',
'aws_access_key_id'),
'aws_secret_access_key': config.get('credentials',
'aws_secret_access_key')
})
if config.has_section('defaults'):
settings['region'] = config.get('defaults', 'region')
return settings