本文整理汇总了Python中six.moves.configparser.RawConfigParser.read方法的典型用法代码示例。如果您正苦于以下问题:Python RawConfigParser.read方法的具体用法?Python RawConfigParser.read怎么用?Python RawConfigParser.read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.configparser.RawConfigParser
的用法示例。
在下文中一共展示了RawConfigParser.read方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _fetchAzureAccountKey
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import read [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))
示例2: main
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import read [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")
示例3: test_upgrade_pstate_files
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import read [as 别名]
def test_upgrade_pstate_files(self):
"""
Test whether the existing pstate files are correctly updated to 7.1.
"""
os.makedirs(os.path.join(self.state_dir, STATEDIR_DLPSTATE_DIR))
# Copy an old pstate file
src_path = os.path.join(self.CONFIG_PATH, "download_pstate_70.state")
shutil.copyfile(src_path, os.path.join(self.state_dir, STATEDIR_DLPSTATE_DIR, "download.state"))
# Copy a corrupt pstate file
src_path = os.path.join(self.CONFIG_PATH, "download_pstate_70_corrupt.state")
corrupt_dest_path = os.path.join(self.state_dir, STATEDIR_DLPSTATE_DIR, "downloadcorrupt.state")
shutil.copyfile(src_path, corrupt_dest_path)
old_config = RawConfigParser()
old_config.read(os.path.join(self.CONFIG_PATH, "tribler70.conf"))
convert_config_to_tribler71(old_config, state_dir=self.state_dir)
# Verify whether the section is correctly renamed
download_config = RawConfigParser()
download_config.read(os.path.join(self.state_dir, STATEDIR_DLPSTATE_DIR, "download.state"))
self.assertTrue(download_config.has_section("download_defaults"))
self.assertFalse(download_config.has_section("downloadconfig"))
self.assertFalse(os.path.exists(corrupt_dest_path))
# Do the upgrade again, it should not fail
convert_config_to_tribler71(old_config, state_dir=self.state_dir)
示例4: test_read_test_tribler_conf
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import read [as 别名]
def test_read_test_tribler_conf(self):
"""
Test upgrading a Tribler configuration from 7.0 to 7.1
"""
old_config = RawConfigParser()
old_config.read(os.path.join(self.CONFIG_PATH, "tribler70.conf"))
new_config = TriblerConfig()
result_config = add_tribler_config(new_config, old_config)
self.assertEqual(result_config.get_default_safeseeding_enabled(), True)
示例5: constructConfigParser
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import read [as 别名]
def constructConfigParser():
"""
returns a pre-setup config parser
"""
parser = RawConfigParser()
parser.read([CONFIG_SYSTEM, CONFIG_USER])
if not parser.has_section(GERALD_CONFIG_SECTION):
parser.add_section(GERALD_CONFIG_SECTION)
return parser
示例6: get_config
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import read [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
示例7: _merge_from_file
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import read [as 别名]
def _merge_from_file(self, config_file):
"""
Merge variables from ``config_file`` into the environment.
Any variables in ``config_file`` that have already been set will be
ignored (meaning this method will *not* try to override them, which
would raise an exception).
If ``config_file`` does not exist or is not a regular file, or if there
is an error parsing ``config_file``, ``None`` is returned.
Otherwise this method returns a ``(num_set, num_total)`` tuple
containing first the number of variables that were actually set, and
second the total number of variables found in ``config_file``.
This method will raise a ``ValueError`` if ``config_file`` is not an
absolute path. For example:
>>> env = Env()
>>> env._merge_from_file('my/config.conf')
Traceback (most recent call last):
...
ValueError: config_file must be an absolute path; got 'my/config.conf'
Also see `Env._merge()`.
:param config_file: Absolute path of the configuration file to load.
"""
if path.abspath(config_file) != config_file:
raise ValueError(
'config_file must be an absolute path; got %r' % config_file
)
if not path.isfile(config_file):
return
parser = RawConfigParser()
try:
parser.read(config_file)
except ParsingError:
return
if not parser.has_section(CONFIG_SECTION):
parser.add_section(CONFIG_SECTION)
items = parser.items(CONFIG_SECTION)
if len(items) == 0:
return (0, 0)
i = 0
for (key, value) in items:
if key not in self:
self[key] = value
i += 1
if 'config_loaded' not in self: # we loaded at least 1 file
self['config_loaded'] = True
return (i, len(items))
示例8: test_read_test_libtribler_conf
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import read [as 别名]
def test_read_test_libtribler_conf(self):
"""
Test upgrading a libtribler configuration from 7.0 to 7.1
"""
os.environ['TSTATEDIR'] = self.session_base_dir
old_config = RawConfigParser()
old_config.read(os.path.join(self.CONFIG_PATH, "libtribler70.conf"))
new_config = TriblerConfig()
result_config = add_libtribler_config(new_config, old_config)
self.assertEqual(result_config.get_tunnel_community_socks5_listen_ports(), [1, 2, 3, 4, 5, 6])
self.assertEqual(result_config.get_anon_proxy_settings(), (2, ("127.0.0.1", [5, 4, 3, 2, 1]), ''))
self.assertEqual(result_config.get_credit_mining_sources(), ['source1', 'source2'])
self.assertEqual(result_config.get_log_dir(), '/a/b/c')
示例9: test_read_test_corr_tribler_conf
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import read [as 别名]
def test_read_test_corr_tribler_conf(self):
"""
Adding corrupt values should result in the default value.
Note that this test might fail if there is already an upgraded config stored in the default
state directory. The code being tested here however shouldn't be ran if that config already exists.
:return:
"""
old_config = RawConfigParser()
old_config.read(os.path.join(self.CONFIG_PATH, "triblercorrupt70.conf"))
new_config = TriblerConfig()
result_config = add_tribler_config(new_config, old_config)
self.assertEqual(result_config.get_default_anonymity_enabled(), True)
示例10: read_cfg
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import read [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')
示例11: get_config
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import read [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
示例12: convert_config_to_tribler71
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import read [as 别名]
def convert_config_to_tribler71(current_config, state_dir=None):
"""
Convert the Config files libtribler.conf and tribler.conf to the newer triblerd.conf and cleanup the files
when we are done.
:param: current_config: the current config in which we merge the old config files.
:return: the newly edited TriblerConfig object with the old data inserted.
"""
state_dir = state_dir or TriblerConfig.get_default_state_dir()
libtribler_file_loc = os.path.join(state_dir, "libtribler.conf")
if os.path.exists(libtribler_file_loc):
libtribler_cfg = RawConfigParser()
libtribler_cfg.read(libtribler_file_loc)
current_config = add_libtribler_config(current_config, libtribler_cfg)
os.remove(libtribler_file_loc)
tribler_file_loc = os.path.join(state_dir, "tribler.conf")
if os.path.exists(tribler_file_loc):
tribler_cfg = RawConfigParser()
tribler_cfg.read(tribler_file_loc)
current_config = add_tribler_config(current_config, tribler_cfg)
os.remove(tribler_file_loc)
# We also have to update all existing downloads, in particular, rename the section 'downloadconfig' to
# 'download_defaults'.
for _, filename in enumerate(iglob(
os.path.join(state_dir, STATEDIR_DLPSTATE_DIR, '*.state'))):
download_cfg = RawConfigParser()
try:
with open(filename) as cfg_file:
download_cfg.readfp(cfg_file, filename=filename)
except MissingSectionHeaderError:
logger.error("Removing download state file %s since it appears to be corrupt", filename)
os.remove(filename)
try:
download_items = download_cfg.items("downloadconfig")
download_cfg.add_section("download_defaults")
for download_item in download_items:
download_cfg.set("download_defaults", download_item[0], download_item[1])
download_cfg.remove_section("downloadconfig")
with open(filename, "w") as output_config_file:
download_cfg.write(output_config_file)
except (NoSectionError, DuplicateSectionError):
# This item has already been converted
pass
return current_config
示例13: CredentialStore
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import read [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()
示例14: main
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import read [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()
示例15: test_read_test_corr_libtribler_conf
# 需要导入模块: from six.moves.configparser import RawConfigParser [as 别名]
# 或者: from six.moves.configparser.RawConfigParser import read [as 别名]
def test_read_test_corr_libtribler_conf(self):
"""
Adding corrupt values should result in the default value.
Note that this test might fail if there is already an upgraded config stored in the default
state directory. The code being tested here however shouldn't be ran if that config already exists.
:return:
"""
old_config = RawConfigParser()
old_config.read(os.path.join(self.CONFIG_PATH, "libtriblercorrupt70.conf"))
new_config = TriblerConfig(ConfigObj(configspec=CONFIG_SPEC_PATH))
result_config = add_libtribler_config(new_config, old_config)
self.assertTrue(len(result_config.get_tunnel_community_socks5_listen_ports()), 5)
self.assertEqual(result_config.get_anon_proxy_settings(), (2, ('127.0.0.1', [-1, -1, -1, -1, -1]), ''))
self.assertEqual(result_config.get_credit_mining_sources(), new_config.get_credit_mining_sources())