本文整理汇总了Python中six.moves.configparser.RawConfigParser.get方法的典型用法代码示例。如果您正苦于以下问题:Python RawConfigParser.get方法的具体用法?Python RawConfigParser.get怎么用?Python RawConfigParser.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.configparser.RawConfigParser
的用法示例。
在下文中一共展示了RawConfigParser.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import get [as 别名]
def main():
logging_config = dict(level=INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
if PY2:
logging_config['disable_existing_loggers'] = True
basicConfig(**logging_config)
args = get_args()
config = RawConfigParser()
config.read(args.configuration)
timestamp = datetime.now().strftime("%H:%M:%S")
machine = gethostname()
if args.no_stamp:
message = args.message
else:
message = "CNC/{machine} [{timestamp}]: {content}".format(machine=machine,
timestamp=timestamp,
content=args.message)
logger.info("Sending message to twitter: %s", message)
tweet(config.get("TWITTER", "CONSUMER_KEY"),
config.get("TWITTER", "CONSUMER_SECRET"),
config.get("TWITTER", "ACCESS_KEY"),
config.get("TWITTER", "ACCESS_SECRET"),
message)
logger.info("Done")
示例2: update_providers
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import get [as 别名]
def update_providers(args, verbose=False):
filepath = args.data_dir.joinpath('references', 'bibtex', 'BIBFILES.ini')
p = RawConfigParser()
with io.open(filepath, encoding='utf-8-sig') as fp:
p.readfp(fp)
provider_map = get_map(Provider)
for section in p.sections():
sectname = section[:-4] if section.endswith('.bib') else section
id_ = slug(sectname)
attrs = {
'name': p.get(section, 'title'),
'description': p.get(section, 'description'),
'abbr': p.get(section, 'abbr'),
}
if id_ in provider_map:
provider = provider_map[id_]
for a in list(attrs):
before, after = getattr(provider, a), attrs[a]
if before == after:
del attrs[a]
else:
setattr(provider, a, after)
attrs[a] = (before, after)
if attrs:
args.log.info('updating provider %s %s' % (slug(id_), sorted(attrs)))
if verbose:
for a, (before, after) in attrs.items():
before, after = (' '.join(_.split()) for _ in (before, after))
if before != after:
args.log.info('%s\n%r\n%r' % (a, before, after))
else:
args.log.info('adding provider %s' % slug(id_))
DBSession.add(Provider(id=id_, **attrs))
示例3: read_cfg
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import get [as 别名]
def read_cfg(self):
parser = RawConfigParser()
parser.read(self.cfg_file)
if not parser.has_section('mail'):
print('Creating cfg file.')
self.make_cfg()
self.auth = parser.get('mail','auth')
self.user = parser.get('mail','username')
self.passwd = parser.get('mail','password')
self.mailfrom = parser.get('mail','mailfrom')
self.host = parser.get('mail','host')
self.port = parser.get('mail','port')
self.tls = parser.get('mail','tls')
示例4: CredentialStore
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import get [as 别名]
class CredentialStore(object):
def __init__(self, **kwargs):
self.credential_search_path = [
os.path.join(os.path.sep, "etc", "cbdefense", "credentials"),
os.path.join(os.path.expanduser("~"), ".cbdefense", "credentials"),
os.path.join(".", ".cbdefense", "credentials"),
]
if "credential_file" in kwargs:
if isinstance(kwargs["credential_file"], six.string_types):
self.credential_search_path = [kwargs["credential_file"]]
elif type(kwargs["credential_file"]) is list:
self.credential_search_path = kwargs["credential_file"]
self.credentials = RawConfigParser(defaults=default_profile)
self.credential_files = self.credentials.read(self.credential_search_path)
def get_credentials(self, profile=None):
credential_profile = profile or "default"
if credential_profile not in self.get_profiles():
raise CredentialError("Cannot find credential profile '%s' after searching in these files: %s." %
(credential_profile, ", ".join(self.credential_search_path)))
retval = {}
for k, v in six.iteritems(default_profile):
retval[k] = self.credentials.get(credential_profile, k)
if not retval["api_key"] or not retval["conn_id"] or not retval["cbd_api_url"]:
raise CredentialError("API Key and Connector ID not available for profile %s" % credential_profile)
return Credentials(retval)
def get_profiles(self):
return self.credentials.sections()
示例5: _fetchAzureAccountKey
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import get [as 别名]
def _fetchAzureAccountKey(accountName):
"""
Find the account key for a given Azure storage account.
The account key is taken from the AZURE_ACCOUNT_KEY_<account> environment variable if it
exists, then from plain AZURE_ACCOUNT_KEY, and then from looking in the file
~/.toilAzureCredentials. That file has format:
[AzureStorageCredentials]
accountName1=ACCOUNTKEY1==
accountName2=ACCOUNTKEY2==
"""
try:
return os.environ['AZURE_ACCOUNT_KEY_' + accountName]
except KeyError:
try:
return os.environ['AZURE_ACCOUNT_KEY']
except KeyError:
configParser = RawConfigParser()
configParser.read(os.path.expanduser(credential_file_path))
try:
return configParser.get('AzureStorageCredentials', accountName)
except NoOptionError:
raise RuntimeError("No account key found for '%s', please provide it in '%s'" %
(accountName, credential_file_path))
示例6: main
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import get [as 别名]
def main():
parser = build_cli_parser("VirusTotal Connector")
parser.add_argument("--config", "-c", help="Path to configuration file", default="virustotal.ini")
args = parser.parse_args()
inifile = RawConfigParser({
"vt_api_key": None,
"retrieve_files": "true",
"upload_binaries_to_vt": "false",
"connector_name": "VirusTotal",
"log_file": None,
})
inifile.read(args.config)
config = {}
config["vt_api_key"] = inifile.get("bridge", "vt_api_key")
config["retrieve_files"] = inifile.getboolean("bridge", "retrieve_files")
config["connector_name"] = inifile.get("bridge", "connector_name")
config["upload_binaries_to_vt"] = inifile.getboolean("bridge", "upload_binaries_to_vt")
log_file = inifile.get("bridge", "log_file")
if log_file:
file_handler = logging.FileHandler(log_file)
formatter = logging.Formatter('%(asctime)s %(levelname)s:%(message)s')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.DEBUG)
logging.getLogger().addHandler(file_handler)
if not config["vt_api_key"]:
log.fatal("Cannot start without a valid VirusTotal API key, exiting")
return 1
log.info("Configuration:")
for k, v in iteritems(config):
log.info(" %-20s: %s" % (k,v))
api = get_cb_protection_object(args)
vt = VirusTotalConnector(
api,
vt_token=config["vt_api_key"],
allow_uploads=config["upload_binaries_to_vt"], # Allow VT connector to upload binary files to VirusTotal
connector_name=config["connector_name"],
)
log.info("Starting VirusTotal processing loop")
vt.run()
示例7: get
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import get [as 别名]
def get(self, section, option):
value = self.DEF_BASE
try:
value = RawConfigParser.get(self, section, option)
except NoSectionError:
pass
except NoOptionError:
pass
return value
示例8: load_config
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import get [as 别名]
def load_config(self, environ):
"""Load configuration options
Options are read from a config file.
Backwards compatibility:
- if ConfigFile is not set, opts are loaded from http config
- if ConfigFile is set, then the http config must not provide Koji options
- In a future version we will load the default hub config regardless
- all PythonOptions (except koji.web.ConfigFile) are now deprecated and
support for them will disappear in a future version of Koji
"""
cf = environ.get('koji.web.ConfigFile', '/etc/kojiweb/web.conf')
cfdir = environ.get('koji.web.ConfigDir', '/etc/kojiweb/web.conf.d')
if cfdir:
configs = koji.config_directory_contents(cfdir)
else:
configs = []
if cf and os.path.isfile(cf):
configs.append(cf)
if configs:
config = RawConfigParser()
config.read(configs)
else:
raise koji.GenericError("Configuration missing")
opts = {}
for name, dtype, default in self.cfgmap:
key = ('web', name)
if config and config.has_option(*key):
if dtype == 'integer':
opts[name] = config.getint(*key)
elif dtype == 'boolean':
opts[name] = config.getboolean(*key)
elif dtype == 'list':
opts[name] = [x.strip() for x in config.get(*key).split(',')]
else:
opts[name] = config.get(*key)
else:
opts[name] = default
opts['Secret'] = koji.util.HiddenValue(opts['Secret'])
self.options = opts
return opts
示例9: get_config
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import get [as 别名]
def get_config(self, path):
"""
Reads entry from configuration.
"""
section, option = path.split('.', 1)
filename = os.path.join(self.path, '.hg', 'hgrc')
config = RawConfigParser()
config.read(filename)
if config.has_option(section, option):
return config.get(section, option).decode('utf-8')
return None
示例10: get_config
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import get [as 别名]
def get_config(self, path):
"""
Reads entry from configuration.
"""
result = None
section, option = path.split(".", 1)
filename = os.path.join(self.path, ".hg", "hgrc")
config = RawConfigParser()
config.read(filename)
if config.has_option(section, option):
result = config.get(section, option)
if six.PY2:
result = result.decode("utf-8")
return result
示例11: set_config
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import get [as 别名]
def set_config(self, path, value):
"""Set entry in local configuration."""
section, option = path.split('.', 1)
filename = os.path.join(self.path, '.hg', 'hgrc')
if six.PY2:
value = value.encode('utf-8')
section = section.encode('utf-8')
option = option.encode('utf-8')
config = RawConfigParser()
config.read(filename)
if not config.has_section(section):
config.add_section(section)
if (config.has_option(section, option) and
config.get(section, option) == value):
return
config.set(section, option, value)
with open(filename, 'w') as handle:
config.write(handle)
示例12: set_config
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import get [as 别名]
def set_config(self, path, value):
"""
Set entry in local configuration.
"""
section, option = path.split(".", 1)
filename = os.path.join(self.path, ".hg", "hgrc")
if six.PY2:
value = value.encode("utf-8")
section = section.encode("utf-8")
option = option.encode("utf-8")
config = RawConfigParser()
config.read(filename)
if not config.has_section(section):
config.add_section(section)
if config.has_option(section, option) and config.get(section, option) == value:
return
config.set(section, option, value)
with open(filename, "w") as handle:
config.write(handle)
示例13: Config
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import get [as 别名]
class Config(object):
"""Configuration class.
:param path: path to configuration file. If no file exists at that location,
the configuration parser will be empty.
"""
def __init__(self, path=expanduser("~/.azkabanrc")):
self.parser = RawConfigParser()
self.path = path
if exists(path):
try:
self.parser.read(self.path)
except ParsingError:
raise AzkabanError("Invalid configuration file %r.", path)
def save(self):
"""Save configuration parser back to file."""
with open(self.path, "w") as writer:
self.parser.write(writer)
def get_option(self, command, name, default=None):
"""Get option value for a command.
:param command: Command the option should be looked up for.
:param name: Name of the option.
:param default: Default value to be returned if not found in the
configuration file. If not provided, will raise
:class:`~azkaban.util.AzkabanError`.
"""
try:
return self.parser.get(command, name)
except (NoOptionError, NoSectionError):
if default is not None:
return default
else:
raise AzkabanError(
"No %(name)s found in %(path)r for %(command)s.\n"
"You can specify one by adding a `%(name)s` option in the "
"`%(command)s` section." % {"command": command, "name": name, "path": self.path}
)
def get_file_handler(self, command):
"""Add and configure file handler.
:param command: Command the options should be looked up for.
The default path can be configured via the `default.log` option in the
command's corresponding section.
"""
handler_path = osp.join(gettempdir(), "%s.log" % (command,))
try:
handler = TimedRotatingFileHandler(
self.get_option(command, "default.log", handler_path),
when="midnight", # daily backups
backupCount=1,
encoding="utf-8",
)
except IOError:
wr.warn("Unable to write to log file at %s." % (handler_path,))
else:
handler_format = "[%(levelname)s] %(asctime)s :: %(name)s :: %(message)s"
handler.setFormatter(lg.Formatter(handler_format))
return handler
示例14: GOAProvidersLoader
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import get [as 别名]
class GOAProvidersLoader(object):
"""
GOA providers reader
"""
def __init__(self, providers_file):
"""
Class initialization
"""
self.path = providers_file
self._providers = {}
self._configparser = RawConfigParser()
try:
self._configparser.read(providers_file)
except IOError as e:
logging.error(
'Could not find GOA providers file %s' % providers_file)
raise e
except ParsingError as e:
logging.error(
'There was an error parsing %s' % providers_file)
raise e
except Exception as e:
logging.error(
'There was an unknown error parsing %s' % providers_file)
raise e
self.read_data()
def read_data(self):
for section in self._configparser.sections():
if section.startswith('Provider '):
provider = section.split()[1]
self._providers[provider] = {
'name': self.generate_readable_name(provider),
'services': {}
}
for option in self._configparser.options(section):
if option == 'providername':
name = self._configparser.get(
section, option)
self._providers[provider]['name'] = name
elif option.endswith('enabled'):
service = option[:-7].title() + 'Enabled'
name = self.generate_readable_name(service[:-7])
enabled = self._configparser.getboolean(
section, option)
# Generate readable name
self._providers[provider]['services'][service] = {
'name': name,
'enabled': enabled
}
def generate_readable_name(self, identifier):
"""
Generates readable names for providers and services
"""
stripped = identifier.strip()
if stripped:
return stripped.title().replace('_', ' ')
else:
return 'Enabled'
def get_providers(self):
return self._providers
示例15: Config
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import get [as 别名]
class Config(object):
"""Configuration class.
:param path: path to configuration file. If no file exists at that location,
the configuration parser will be empty. Defaults to `~/.azkabanrc`.
"""
def __init__(self, path=None):
self.parser = RawConfigParser()
self.path = path or expanduser('~/.azkabanrc')
# TODO: make the default path be configurable via an environment variable.
if exists(self.path):
try:
self.parser.read(self.path)
except ParsingError:
raise AzkabanError('Invalid configuration file %r.', self.path)
else:
# TODO: remove this in 1.0.
if self._convert_aliases():
self.save()
self.parser.read(self.path)
def save(self):
"""Save configuration parser back to file."""
with open(self.path, 'w') as writer:
self.parser.write(writer)
def get_option(self, command, name, default=None):
"""Get option value for a command.
:param command: Command the option should be looked up for.
:param name: Name of the option.
:param default: Default value to be returned if not found in the
configuration file. If not provided, will raise
:class:`~azkaban.util.AzkabanError`.
"""
try:
return self.parser.get(command, name)
except (NoOptionError, NoSectionError):
if default is not None:
return default
else:
raise AzkabanError(
'No %(name)s found in %(path)r for %(command)s.\n'
'You can specify one by adding a `%(name)s` option in the '
'`%(command)s` section.'
% {'command': command, 'name': name, 'path': self.path}
)
def get_file_handler(self, command):
"""Add and configure file handler.
:param command: Command the options should be looked up for.
The default path can be configured via the `default.log` option in the
command's corresponding section.
"""
handler_path = osp.join(gettempdir(), '%s.log' % (command, ))
try:
handler = TimedRotatingFileHandler(
self.get_option(command, 'default.log', handler_path),
when='midnight', # daily backups
backupCount=1,
encoding='utf-8',
)
except IOError:
wr.warn('Unable to write to log file at %s.' % (handler_path, ))
else:
handler_format = '[%(levelname)s] %(asctime)s :: %(name)s :: %(message)s'
handler.setFormatter(lg.Formatter(handler_format))
return handler
def _convert_aliases(self):
"""Convert old-style aliases to new-style."""
parser = self.parser
if not parser.has_section('alias'):
return False # Nothing to do.
for alias, url in parser.items('alias'):
section = 'alias.%s' % (alias, )
if not parser.has_section(section):
# Only update if the alias doesn't yet.
parser.add_section(section)
parser.set(section, 'url', url)
parser.set(section, 'verify', 'false') # Backwards compatibility.
parser.remove_section('alias')
return True