本文整理汇总了Python中ConfigParser.ConfigParser.optionxform方法的典型用法代码示例。如果您正苦于以下问题:Python ConfigParser.optionxform方法的具体用法?Python ConfigParser.optionxform怎么用?Python ConfigParser.optionxform使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConfigParser.ConfigParser
的用法示例。
在下文中一共展示了ConfigParser.optionxform方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: read
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import optionxform [as 别名]
def read(self, filename):
# clean the sections
for section in self.keys():
del self[section]
from ConfigParser import ConfigParser
config = ConfigParser()
config.optionxform = str
config.read(filename)
for this in config.sections():
sec = eval("Params" + this + "()")
options = config.options(this)
for option in options:
value = config.get(this, option)
# HERE, we need to interpret the content of the config file.
# values could be int or float, in which case we want to cast the string
# to a float. If the string is True/False, we want also a cast
try:
try:
value = int(value)
except:
value = float(value)
except:
if isinstance(value, str):
if value == 'True':
value = True
elif value == 'False':
value = False
elif value.strip() == '':
value = None
setattr(getattr(sec, option), 'value', value)
self[this] = sec
return config
示例2: config
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import optionxform [as 别名]
def config(self, key=None, default=u""):
"""
Return the configuration file location or values of keys.
"""
# First try a direct environment variable.
try: fn = os.environ["IMPERIAL_CONFIG"]
except KeyError:
# Next, are we on Windows?
if SHGetFolderPath: fn = SHGetFolderPath(0, CSIDL_APPDATA, None, 0) + "\\imperial.ini"
# Or Linux? (God I hope this works on Mac, too!)
elif xdg_config_home: fn = os.path.join(xdg_config_home, ".imperial")
# Something else..? (Bonus points: it even fits 8.3)
else: fn = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), "imperial" + os.extsep + "ini")
#endtry
if key is None: return fn
else:
config = ConfigParser()
config.optionxform = str
config.read(fn)
if type(key) in [str, unicode]:
try: ret = config.get("Imperial", key)
except (NoSectionError, NoOptionError): ret = default
else:
ret = {}
for x in key:
try: ret[x] = (config.get("Imperial", x))
except (NoSectionError, NoOptionError):
# Passed defaults by dict.
try: ret[x] = key[x]
# No explicit defaulting.
except TypeError: ret[x] = u""
#endtry
#endfor
return ret
示例3: confFileFromDB
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import optionxform [as 别名]
def confFileFromDB(gt, gtConfFileName, gtConnString, authpath):
# check if the original conf file exists
if not os.path.isfile(gtConfFileName):
# get the conf file from DB
print "Getting the conf file for GT: " + gt + " from DB....be patinet!"
dbtoconf_cfg = ConfigParser()
dbtoconf_cfg.optionxform = str
dbtoconf_cfg.add_section("Common")
dbtoconf_cfg.set("Common","Account","CMS_COND_31X_GLOBALTAG")
#dbtoconf_cfg.set("Common","Conn_string_gtag","frontier://cmsfrontier:8000/FrontierProd/CMS_COND_31X_GLOBALTAG")
dbtoconf_cfg.set("Common","Conn_string_gtag",gtConnString)
dbtoconf_cfg.set("Common","AuthPath",authpath)
dbtoconf_cfg.set("Common","Globtag",gt)
dbtoconf_cfg.set("Common","Confoutput",gtConfFileName)
dbtoconf_file = open("dbtoconf.cfg", 'wb')
dbtoconf_cfg.write(dbtoconf_file)
dbtoconf_file.close()
#dbtoconf_cmd = 'eval `scram runtime -csh`; dbtoconf.py'
dbtoconf_cmd = 'dbtoconf.py'
statusAndOutput = commands.getstatusoutput(dbtoconf_cmd)
if statusAndOutput[0] != 0:
print statusAndOutput[1]
# check again
if not os.path.isfile(gtConfFileName):
return False
return True
示例4: __init__
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import optionxform [as 别名]
def __init__(self, config_file='config.ini'):
parser = ConfigParser()
parser.optionxform=str
parser.read(config_file)
self.config = {}
for section in parser.sections():
self.config[section] = {}
for key, val in parser.items(section):
if section == "Aggregations":
try:
val = json.loads(val)
except:
raise Exception(
"Could not parse aggregation {}:\n{}".format(
key,
val
)
)
self.config[section][key] = val
if not 'Authentication' in self.config:
raise Exception("Configuration missing Authentication section")
elif not 'auth_token' in self.config['Authentication']:
raise Exception("Authentication section missing auth_token")
elif len(str(self.config['Authentication']['auth_token'])) < 30:
raise Exception("Invalid auth_token")
self.hipchat = hypchat.HypChat(
self.config['Authentication']['auth_token']
)
self.get_self()
self.make_rooms()
示例5: downloadTweets
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import optionxform [as 别名]
def downloadTweets(username, downloadNewerThanId=-1, downloadOlderThanId=999999999999999999):
highestIdDownloaded = 0
storedInfo = ConfigParser()
storedInfo.optionxform = str #Makes sure options preserve their case. Prolly breaks something down the line, but CASE!
twitterInfoFilename = os.path.join(GlobalStore.scriptfolder, 'data', 'TwitterInfo.dat')
if os.path.exists(twitterInfoFilename):
storedInfo.read(twitterInfoFilename)
if not storedInfo.has_section(username):
storedInfo.add_section(username)
if storedInfo.has_option(username, "highestIdDownloaded"):
highestIdDownloaded = int(storedInfo.get(username, "highestIdDownloaded"))
headers = {"Authorization": "{} {}".format(GlobalStore.commandhandler.apikeys.get('twitter', 'tokentype'), GlobalStore.commandhandler.apikeys.get('twitter', 'token'))}
params = {"screen_name": username, "count": "200", "trim_user": "true", "exclude_replies": "true", "include_rts": "false"}
if downloadNewerThanId > -1:
params["since_id"] = downloadNewerThanId
tweets = {}
lowestIdFound = downloadOlderThanId
newTweetsFound = True
while newTweetsFound:
params["max_id"] = lowestIdFound
req = requests.get("https://api.twitter.com/1.1/statuses/user_timeline.json", headers=headers, params=params)
apireply = json.loads(req.text)
newTweetsFound = False
for tweet in apireply:
tweettext = tweet["text"].replace("\n", " ").encode(encoding="utf-8", errors="replace")
#print "Tweet {}: {}".format(tweet["id"], tweettext)
if tweet["id"] not in tweets:
#print " storing tweet"
newTweetsFound = True
tweets[tweet["id"]] = tweettext
tweetId = int(tweet["id"])
lowestIdFound = min(lowestIdFound, tweetId-1)
highestIdDownloaded = max(highestIdDownloaded, tweetId)
#else:
# print " skipping duplicate tweet"
#All tweets downloaded. Time to process them
tweetfile = open(os.path.join(GlobalStore.scriptfolder, 'data', "tweets-{}.txt".format(username)), "a")
#Sort the keys before saving, so we're writing from oldest to newest, so in the same order as the Twitter timeline (Not absolutely necessary, but it IS neat and tidy)
for id in sorted(tweets.keys()):
tweetfile.write(tweets[id] + "\n")
tweetfile.close()
storedInfo.set(username, "highestIdDownloaded", highestIdDownloaded)
linecount = 0
if storedInfo.has_option(username, "linecount"):
linecount = storedInfo.getint(username, "linecount")
linecount += len(tweets)
storedInfo.set(username, "linecount", linecount)
storedInfoFile = open(twitterInfoFilename, "w")
storedInfo.write(storedInfoFile)
storedInfoFile.close()
return True
示例6: prepareExport
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import optionxform [as 别名]
def prepareExport(self,fName='migration.ini'):
"""
create an ini file that is used for exporting files.
file is saved in the root folder
"""
# create export mapping (source->dest). this is a multiline string
mapping = '\n'
for oldPath in self.folders():
mapping+='->'.join((oldPath, newPath(oldPath,self.dateRange(oldPath))))+'\n'
p = ConfigParser()
p.optionxform = str
p.add_section('Export')
p.set('Export','root',self.root)
p.set('Export','dest',None)
p.set('Export','mapping',mapping)
self.log.info( 'Writing '+fName)
with open(fName,'w') as fid:
p.write(fid)
示例7: loadEmailConf
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import optionxform [as 别名]
def loadEmailConf():
""" Load configuration parameters to be used for emailing.
By default read from: scipion.conf
"""
# Read menus from users' config file.
cp = ConfigParser()
cp.optionxform = str # keep case (stackoverflow.com/questions/1611799)
emailConf = OrderedDict()
confFile = os.environ['SCIPION_CONFIG']
assert cp.read(confFile) != [], 'Missing file %s' % confFile
# Set options from EMAIL main section
def setm(option, default):
if cp.has_option('EMAIL', option):
emailConf[option] = cp.get('EMAIL', option)
else:
emailConf[option] = default
setm('EMAIL_HOST', 'localhost')
setm('EMAIL_PORT', '25')
setm('EMAIL_HOST_USER', 'smtpuser')
setm('EMAIL_HOST_PASSWORD', 'smtppassword')
setm('EMAIL_USE_TLS', False)
setm('EMAIL_FOR_SUBSCRIPTION', '[email protected]')
return emailConf
示例8: getDataSources
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import optionxform [as 别名]
def getDataSources(fName = None):
''' return data sources directories for this machine.
directories are defined in datasources.ini or provided filepath'''
import socket
from ConfigParser import ConfigParser
pcName = socket.gethostname()
p = ConfigParser()
p.optionxform = str
if fName is None:
fName = 'datasources.ini'
p.read(fName)
if pcName not in p.sections():
raise NameError('Host name section %s not found in file %s' %(pcName,fName))
dataSources = {}
for option in p.options(pcName):
dataSources[option] = p.get(pcName,option)
return dataSources
示例9: fromIniFile
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import optionxform [as 别名]
def fromIniFile(iniFilename, sectionName):
iniFilename = op.abspath(op.expanduser(iniFilename))
def resolvePath(path):
"""
Path may be given
- as relative to the ini file path
- qualified with "~"
Resolve it whatever it is.
None is passed through.
"""
if path is None: return None
iniDirectory = op.dirname(iniFilename)
path = op.expanduser(path)
if op.isabs(path):
return path
else:
return op.abspath(op.join(iniDirectory, path))
cp = ConfigParser()
cp.optionxform=str
cp.read(iniFilename)
opts = dict(cp.items(sectionName))
return Fixture(trcFname=resolvePath(opts.get("Traces")),
plsFname=resolvePath(opts.get("Pulses")),
basFname=resolvePath(opts.get("Bases")),
refFname=resolvePath(opts.get("Reference")),
alnFname=resolvePath(opts.get("Alignments")))
示例10: test_read_init
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import optionxform [as 别名]
def test_read_init(self):
"""Test that the plugin __init__ will validate on plugins.qgis.org."""
# You should update this list according to the latest in
# https://github.com/qgis/qgis-django/blob/master/qgis-app/
# plugins/validator.py
required_metadata = [
'name',
'description',
'version',
'qgisMinimumVersion',
'email',
'author']
file_path = os.path.abspath(os.path.join(
os.path.dirname(__file__), os.pardir,
'metadata.txt'))
LOGGER.info(file_path)
metadata = []
parser = ConfigParser()
parser.optionxform = str
parser.read(file_path)
message = 'Cannot find a section named "general" in %s' % file_path
assert parser.has_section('general'), message
metadata.extend(parser.items('general'))
for expectation in required_metadata:
message = ('Cannot find metadata "%s" in metadata source (%s).' % (
expectation, file_path))
self.assertIn(expectation, dict(metadata), message)
示例11: createDictFromConfig
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import optionxform [as 别名]
def createDictFromConfig():
""" Read the configuration from scipion/config/scipionbox.conf.
A dictionary will be created where each key will be a section starting
by MICROSCOPE:, all variables that are in the GLOBAL section will be
inherited by default.
"""
# Read from users' config file.
confGlobalDict = OrderedDict()
confDict = OrderedDict()
cp = ConfigParser()
cp.optionxform = str # keep case (stackoverflow.com/questions/1611799)
confFile = pw.getConfigPath("scipionbox.conf")
print "Reading conf file: ", confFile
cp.read(confFile)
GLOBAL = "GLOBAL"
MICROSCOPE = "MICROSCOPE:"
if not GLOBAL in cp.sections():
raise Exception("Missing section %s in %s" % (GLOBAL, confFile))
else:
for opt in cp.options(GLOBAL):
confGlobalDict[opt] = cp.get(GLOBAL, opt)
for section in cp.sections():
if section != GLOBAL and section.startswith(MICROSCOPE):
sectionDict = OrderedDict(confGlobalDict)
for opt in cp.options(section):
sectionDict[opt] = cp.get(section, opt)
confDict[section.replace(MICROSCOPE, '')] = sectionDict
return confDict
示例12: dict_conf
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import optionxform [as 别名]
def dict_conf(filename):
"""
Return dict object for *.conf file
"""
f, ext = os.path.splitext(filename)
ext = ext.lower()
if ext == "conf" or ext == "ini":
# python config via config parser
config = ConfigParser()
config.optionxform=str
config.read(filename)
rv = {}
for section in config.sections():
rv[section] = {}
for key,value in config.items(section):
rv[section][key] = value.strip('"').strip("'").decode("string_escape")
return rv
else:
# other type of config, use munge
if munge_config:
src = munge_config.parse_url(filename)
return src.cls().load(open(filename)).get("vodka")
else:
raise Exception("'%s' type of config encountered, install munge" % ext)
示例13: loadWebConf
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import optionxform [as 别名]
def loadWebConf():
""" Load configuration parameters to be used in web.
By default read from: scipion.conf
"""
# Read menus from users' config file.
cp = ConfigParser()
cp.optionxform = str # keep case (stackoverflow.com/questions/1611799)
webConf = OrderedDict()
confFile = os.environ['SCIPION_CONFIG']
assert cp.read(confFile) != [], 'Missing file %s' % confFile
# Set options from WEB main section
def setw(option, default):
if cp.has_option('WEB', option):
webConf[option] = cp.get('WEB', option)
else:
webConf[option] = default
setw('SITE_URL', 'scipion.cnb.csic.es')
setw('ABSOLUTE_URL', '')
# Load some parameters per protocol
protocols = OrderedDict()
webConf['PROTOCOLS'] = protocols
if cp.has_section('WEB_PROTOCOLS'):
for protName in cp.options('WEB_PROTOCOLS'):
protocols[protName] = json.loads(cp.get('WEB_PROTOCOLS', protName))
return webConf
示例14: parse_config_file
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import optionxform [as 别名]
def parse_config_file(config_type, config_filename):
from ConfigParser import ConfigParser
config_dic = {}
if not os.path.exists(config_filename):
print "%s: Error: %s config file does not exist [%s]" % (time.strftime("%H:%M:%S"), config_type, config_filename)
config_dic['CONFIG_EXISTS'] = False
else:
config_dic['CONFIG_EXISTS'] = True
# get global config values
parser_dic = ConfigParser()
parser_dic.optionxform = str
parser_dic.read(config_filename)
if DEBUG:
print "\t>> %s Config file: %s" % (config_type, config_filename)
# print "\t >> %s Sections %s" % (config_type, parser_dic.sections())
for section_name in parser_dic.sections():
if DEBUG:
print '\t >> %s Section: %s' % (config_type, section_name)
# print '\t >> %s Options: %s' % (config_type, parser_dic.options(section_name))
for name, value in parser_dic.items(section_name):
if DEBUG:
print '\t >> %s Value: %s = %s' % (config_type, name, value)
config_dic[name] = value
return config_dic
示例15: read_rss_feeds_ini
# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import optionxform [as 别名]
def read_rss_feeds_ini(rss_ini, verbose=False):
sources = []
if rss_ini is None:
rss_ini = os.getenv("NB_RSS", None)
if rss_ini is None:
return sources
else:
from ConfigParser import ConfigParser
parser = ConfigParser(allow_no_value=True)
parser.optionxform = str
parser.read(rss_ini)
for source_url in parser.sections():
http_source_url = "http://" + source_url
if verbose:
print u"SOURCE:", http_source_url, u"\nFEEDS:"
source = Source(http_source_url)
sources.append(source)
for rss_url, _ in parser.items(source_url):
http_rss_url = "http://" + rss_url
if verbose:
print u"\t", http_rss_url
source.feeds.append(
Feed(http_rss_url))
return sources