本文整理汇总了Python中myutils.BetterConfigParser.read方法的典型用法代码示例。如果您正苦于以下问题:Python BetterConfigParser.read方法的具体用法?Python BetterConfigParser.read怎么用?Python BetterConfigParser.read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类myutils.BetterConfigParser
的用法示例。
在下文中一共展示了BetterConfigParser.read方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _setup_configfiles
# 需要导入模块: from myutils import BetterConfigParser [as 别名]
# 或者: from myutils.BetterConfigParser import read [as 别名]
def _setup_configfiles(self, Testboard):
""" Changes config files in the already copied test directory according to test definitions
from elComandante's init file. """
# Delete all root files which are already in the directory
root_files = glob.glob(Testboard.testdir+'/*.root')
for f in root_files:
os.remove(f)
# Change testboard name
if Testboard.DTB and os.path.isfile(Testboard.testdir + "/tb"):
self._config_file_content_substitute(Testboard.testdir + "/tb", {"id":Testboard.address})
else:
self._config_file_content_substitute(Testboard.testdir + "/configParameters.dat", {"testboardName":Testboard.address})
# Get test specific config parameters (if available)
params = ()
try:
params = self.init.items("Test " + self.test.testname)
except:
return
for par in params:
file = par[0]
if '.cfg' in file:
section,pair = par[1].split(':')
key,value = pair.split('=')
config_file = BetterConfigParser()
config_file.read(Testboard.testdir + "/" + file)
config_file.set(section,key,value)
write_file = open(Testboard.testdir + "/" + file, 'write')
config_file.write(write_file)
write_file.close()
continue
# Check for valid keys that represent config files
elif "testParameters" in file or "dacParameters" in file or "configParameters" in file:
pass
elif "tbmParameters" in file or "tbParameters" in file:
pass
else:
continue
encoded_keys = par[1].split(",")
keys = {}
for key in encoded_keys:
key = key.split("=", 2)
if len(key) != 2:
continue
keys[key[0]] = key[1]
if len(file) < 4 or file[-4:] != ".dat":
file += ".dat"
self._config_file_content_substitute(Testboard.testdir + "/" + file, keys)
示例2: diffConfigFile
# 需要导入模块: from myutils import BetterConfigParser [as 别名]
# 或者: from myutils.BetterConfigParser import read [as 别名]
def diffConfigFile(tag1, tag2, fileName):
print("file:", fileName)
config1 = BetterConfigParser()
config2 = BetterConfigParser()
config1.read(tag1 + 'config/' + fileName)
config2.read(tag2 + 'config/' + fileName)
sections = list(set(config1.sections() + config2.sections()))
commonSections = [x for x in sections if x in config1.sections() and x in config2.sections()]
print("common sections:", commonSections)
for section in commonSections:
firstItemInSection = True
items1d = {x[0]:x[1] for x in config1.items(section, raw=True)}
items2d = {x[0]:x[1] for x in config2.items(section, raw=True)}
items1 = [x[0] for x in config1.items(section, raw=True)]
items2 = [x[0] for x in config2.items(section, raw=True)]
items = list(set(items1 + items2))
commonItems = list(set([x for x in items if x in items1 and x in items2]))
for item in commonItems:
if item not in os.environ:
try:
item1 = config1.get(section, item)
item2 = config2.get(section, item)
item1 = items1d[item]
item2 = items2d[item]
if item1 != item2:
if firstItemInSection:
firstItemInSection = False
print('-'*80)
print(' \x1b[34m' + fileName + '\x1b[0m: ' + section)
print('-'*80)
print(section + ':' + item)
d = difflib.Differ()
result = list(d.compare([item1], [item2]))
for line in result:
if line.startswith('+'):
color = '\x1b[31m'
elif line.startswith('-'):
color = '\x1b[32m'
elif line.startswith('?'):
color = '\x1b[34m'
print(' '+color+line+'\x1b[0m')
except Exception as e:
pass
示例3: len
# 需要导入模块: from myutils import BetterConfigParser [as 别名]
# 或者: from myutils.BetterConfigParser import read [as 别名]
#adds the file vhbbPlotDef.ini to the config list
#print 'opts.config',opts.config
# print 'opts.filelist="'+opts.filelist+'"'
filelist=filter(None,opts.filelist.replace(' ', '').split(';'))
# print filelist
print "len(filelist)",len(filelist),
if len(filelist)>0:
print "filelist[0]:",filelist[0];
else:
print ''
vhbbPlotDef=opts.config[0].split('/')[0]+'/vhbbPlotDef.ini'
opts.config.append(vhbbPlotDef)#adds it to the config list
config = BetterConfigParser()
config.read(opts.config)
#path = opts.path
region = opts.region
# additional blinding cut:
addBlindingCut = None
if config.has_option('Plot_general','addBlindingCut'):#contained in plots, cut on the event number
addBlindingCut = config.get('Plot_general','addBlindingCut')
print 'adding add. blinding cut'
print "Compile external macros"
print "=======================\n"
#get locations:
Wdir=config.get('Directories','Wdir')# working direcoty containing the ouput
示例4: countEvents
# 需要导入模块: from myutils import BetterConfigParser [as 别名]
# 或者: from myutils.BetterConfigParser import read [as 别名]
#print extPart,"=>",len(extPartFiles),"files"
extPartCounts[extPart] = 0
for extPartFile in extPartFiles:
extPartCounts[extPart] += countEvents(t3proto + '/' + extPartFile)
#root://t3dcachedb03.psi.ch:1094
# get total count
totalCount = sum([n for sampleName,n in extPartCounts.iteritems()])
# relative weights
for sampleName,n in extPartCounts.iteritems():
print sampleName,":",(1.0*n/totalCount if totalCount > 0 else '-')
config = BetterConfigParser()
configPath = sys.argv[1] + '/samples_nosplit.ini'
config.read(configPath)
configPath = sys.argv[1] + '/paths.ini'
config.read(configPath)
sampleDict = {}
sampleWeights = {}
verify = len(sys.argv) > 2 and sys.argv[2]=='verify'
##############
#Specialweight
##############
#ZLLIncl = ["DYJetsToLL_M-50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_ext1","DYJetsToLL_M-50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_ext2"]
#
#ZLLjetsHT0 = ["DYJetsToLL_M-50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_ext1"]
##ZLLjetsHT70 = ["DYJetsToLL_M-50_HT-70to100_TuneCUETP8M1_13TeV-madgraphMLM-pythia8"]
示例5: OptionParser
# 需要导入模块: from myutils import BetterConfigParser [as 别名]
# 或者: from myutils.BetterConfigParser import read [as 别名]
from optparse import OptionParser
from myutils import BetterConfigParser, copytree, ParseInfo
argv = sys.argv
#get files info from config
parser = OptionParser()
parser.add_option("-C", "--config", dest="config", default=[], action="append",
help="directory config")
parser.add_option("-S", "--samples", dest="names", default="",
help="samples you want to run on")
(opts, args) = parser.parse_args(argv)
config = BetterConfigParser()
config.read(opts.config)
namelist=opts.names.split(',')
pathIN = config.get('Directories','PREPin')
pathOUT = config.get('Directories','PREPout')
samplesinfo=config.get('Directories','samplesinfo')
sampleconf = BetterConfigParser()
sampleconf.read(samplesinfo)
prefix=sampleconf.get('General','prefix')
info = ParseInfo(samplesinfo,pathIN)
for job in info:
if not job.name in namelist:
示例6: BetterConfigParser
# 需要导入模块: from myutils import BetterConfigParser [as 别名]
# 或者: from myutils.BetterConfigParser import read [as 别名]
print "Please provide a task.\n-J prep:\tpreparation of Trees\n-J sys:\t\twrite regression and systematics\n-J eval:\tcreate MVA output\n-J plot:\tproduce Plots\n-J dc:\t\twrite workspaces and datacards"
sys.exit(123)
en = opts.tag
#create the list with the samples to run over
samplesList=opts.samples.split(",")
timestamp = time.asctime().replace(' ','_').replace(':','-')
if(debugPrintOUts): print 'samplesList',samplesList
if(debugPrintOUts): print 'timestamp',timestamp
# the list of the config is taken from the path config
pathconfig = BetterConfigParser()
pathconfig.read('%sconfig/paths'%(en))
_configs = pathconfig.get('Configuration','List').split(" ")
configs = [ '%sconfig/'%(en) + c for c in _configs ]
if(debugPrintOUts): print 'configs',configs
if(debugPrintOUts): print 'opts.ftag',opts.ftag
if not opts.ftag == '':
tagDir = pathconfig.get('Directories','tagDir')
# DEBUG PURPOSE ONLY
# sys.exit()
if(debugPrintOUts): print 'tagDir',tagDir
DirStruct={'tagDir':tagDir,'ftagdir':'%s/%s/'%(tagDir,opts.ftag),'logpath':'%s/%s/%s/'%(tagDir,opts.ftag,'Logs'),'plotpath':'%s/%s/%s/'%(tagDir,opts.ftag,'Plots'),'limitpath':'%s/%s/%s/'%(tagDir,opts.ftag,'Limits'),'confpath':'%s/%s/%s/'%(tagDir,opts.ftag,'config') }
if(debugPrintOUts): print 'DirStruct',DirStruct
示例7: printer
# 需要导入模块: from myutils import BetterConfigParser [as 别名]
# 或者: from myutils.BetterConfigParser import read [as 别名]
parser.add_argument("-num","--numTB", dest="numTB",
help="specify the number of Testboards in use",
default="1")
#parse args and setup logdir
args = parser.parse_args()
Logger = printer()
Logger.set_name("Psi46Log")
Logger.set_prefix('')
Logger.set_logfile('%s'%(args.loggingDir),'psi46Handler.log')
Logger <<'ConfigDir: "%s"'%args.configDir
configDir= args.configDir
numTB = int(args.numTB)
#load config
config = BetterConfigParser()
config.read(configDir+'/elComandante.conf')
#config
clientName = "psi46"
serverZiel=config.get('subsystem','Ziel')
Port = int(config.get('subsystem','Port'))
serverPort = int(config.get('subsystem','Port'))
psiSubscription = config.get('subsystem','psiSubscription')
errorSubscription = "/error"
#construct
client = sClient(serverZiel,serverPort,clientName)
#subscribe
client.subscribe(psiSubscription)
#----------------------------------------------------
#handler
def handler(signum, frame):
示例8: TBmaster
# 需要导入模块: from myutils import BetterConfigParser [as 别名]
# 或者: from myutils.BetterConfigParser import read [as 别名]
class TBmaster(object):
def __init__(self, TB, client, psiSubscription, Logger, color='black', psiVersion='psi46expert'):
self.TB = TB
self.client = client
self.psiSubscription = psiSubscription
self.color = color
self.Logger = Logger
self.TBSubscription = '/TB%s'%self.TB
self.client.subscribe(self.TBSubscription)
self.dir = ''
self.psiVersion = psiVersion
if self.psiVersion.lower().endswith("psi46expert"):
self.version ='psi46expert'
elif self.psiVersion.lower().endswith("pyxar"):
self.version ='pyxar'
elif self.psiVersion.lower().endswith("pxar"):
self.version ='pxar'
else:
self.version = 'unknown'
self.failed = False
self.busy = False
self.testName ='unkown'
self.testNo = -1
self.TestEnd = False
self.DoTest= False
self.ClosePSI= False
self.Abort = False
self.LogFile = ""
self.RootFile = ""
# default value in Vcal units, -1 means use untrimmed parameters
# this setting is overwritten if [Test Trim] is specified in the ini file
# containg testParameters=Vcal=*
self.trimVcal = -1
self.init = BetterConfigParser()
self.init.read("../config/elComandante.ini")
try:
testParameters = self.init.get('Test Trim','testParameters')
pos1 = testParameters.find("=")
if pos1 > 0:
testParametersName = testParameters[0:pos1]
testParametersValue = testParameters[pos1+1:]
if testParametersName.lower() == "vcal":
self.trimVcal = int(testParametersValue)
self.Logger << "TB%s: using option '-T %s' when calling pxar"%(self.TB, self.trimVcal)
except:
self.Logger << "TB%s: no [Test Trim] section found in ini file, using untrimmed parameters"%self.TB
def _spawn(self,executestr):
my_env = os.environ
if my_env.has_key("LD_PRELOAD"):
my_env["LD_PRELOAD"] = "/opt/glibc-2.14/lib/libc.so.6:" + my_env["LD_PRELOAD"]
else:
my_env["LD_PRELOAD"] = "/opt/glibc-2.14/lib/libc.so.6:"
self.proc = subprocess.Popen([executestr,''], shell = True, stdout = subprocess.PIPE, stdin = subprocess.PIPE, env = my_env)
self.busy = True
def _kill(self):
try:
self.proc.kill()
self.Logger.warning("PSI%s KILLED"%self.TB)
except:
self.Logger.warning("nothing to be killed")
def _abort(self):
self.Logger.warning('ABORT!')
self._kill()
self.Abort = False
return True
def _resetVariables(self):
self.busy = False
self.failed = False
self.TestEnd = False
self.DoTest = False
self.ClosePSI = False
self.Abort = False
def _readAllSoFar(self, retVal = ''):
while (select.select([self.proc.stdout],[],[],0)[0]!=[]) and self.proc.poll() is None:
retVal += self.proc.stdout.read(1)
return retVal
@staticmethod
def findError(stat):
return any([Error in stat for Error in ['error','Error','anyOtherString','command not found']])
def _readout(self):
internalFailed = False
self.Logger << '>>> Aquire Testboard %s <<<'%self.TB
# self._answer(self)
while self.proc.poll() is None and self.ClosePSI==False:
if self.Abort:
internalFailed = self._abort()
lines = ['']
lines = self._readAllSoFar(lines[-1]).split('\n')
for a in range(len(lines)-1):
line=lines[a]
hesays=line.rstrip()
self.client.send(self.TBSubscription,'%s\n'%hesays)
#.........这里部分代码省略.........
示例9: drawFromDC
# 需要导入模块: from myutils import BetterConfigParser [as 别名]
# 或者: from myutils.BetterConfigParser import read [as 别名]
def drawFromDC():
config = BetterConfigParser()
config.read(opts.config)
region = opts.region
print "\nopts.config:",opts.config
print "opts:", opts
print "var:", opts.var
print "bin:", opts.bin
dataname = 'Zll'
if 'Zmm' in opts.bin: dataname = 'Zmm'
elif 'Zee' in opts.bin: dataname = 'Zee'
elif 'Wmunu' in opts.bin: dataname = 'Wmn'
elif 'Wenu' in opts.bin: dataname = 'Wen'
elif 'Znunu' in opts.bin: dataname = 'Znn'
elif 'Wtn' in opts.bin: dataname = 'Wtn'
if (opts.var == ''):
var = 'BDT'
if dataname == 'Zmm' or dataname == 'Zee': var = 'BDT_Zll'
elif dataname == 'Wmn' or dataname == 'Wen': var = 'BDT_Wln'
elif dataname == 'Znn':
if 'HighPt' in opts.bin: var = 'BDT_ZnnHighPt'
if 'LowPt' in opts.bin: var = 'BDT_ZnnLowPt'
if 'LowCSV' in opts.bin: var = 'BDT_ZnnLowCSV'
if dataname == '' or var == 'BDT': raise RuntimeError, 'Did not recognise mode or var from '+opts.bin
else:
var = opts.var
if 'BDT' in var:
region = 'BDT'
else:
region = opts.bin
ws_var = config.get('plotDef:%s'%var,'relPath')
if region == 'BDT':
ws_var = ROOT.RooRealVar(ws_var,ws_var,-1.,1.)
else:
ws_var = ROOT.RooRealVar(ws_var,ws_var, 0, 1.)
blind = eval(config.get('Plot:%s'%region,'blind'))
print 'config:', config
print 'var: ', var
print 'region: ', region
Stack=StackMaker(config,var,region,True)
if 'LowPt' in opts.bin or 'ch1_Wenu' == opts.bin or 'ch2_Wmunu' == opts.bin:
Stack.addFlag2 = 'Low p_{T}(V)'
elif 'MedPt' in opts.bin or 'ch1_Wenu2' == opts.bin or 'ch2_Wmunu2' == opts.bin:
Stack.addFlag2 = 'Intermediate p_{T}(V)'
elif 'HighPt' in opts.bin or 'ch1_Wenu3' == opts.bin or 'ch2_Wmunu3' == opts.bin:
Stack.addFlag2 = 'High p_{T}(V)'
# check for pre or post fit options
preFit = False
addName = 'PostFit_%s' %(opts.fit)
if not opts.mlfit:
addName = 'PreFit'
preFit = True
print '\n-----> Fit Type(opts.fit) : ', opts.fit
print ' (opts.mlfit): ', opts.mlfit
print ' preFit : ', preFit
Stack.options['pdfName'] = '%s_%s_%s.pdf' %(var,opts.bin,addName)
log = eval(config.get('Plot:%s'%region,'log'))
setup = config.get('Plot_general','setup').split(',')
if dataname == 'Zmm' or dataname == 'Zee':
try:
setup.remove('W1b')
setup.remove('W2b')
setup.remove('Wlight')
setup.remove('WH')
except:
print '@INFO: Wb / Wligh / WH not present in the datacard'
if not dataname == 'Znn' and 'QCD' in setup:
setup.remove('QCD')
Stack.setup = setup
Dict = eval(config.get('LimitGeneral','Dict'))
lumi = eval(config.get('Plot_general','lumi'))
options = copy(opts)
options.dataname = "data_obs"
options.mass = 0
options.format = "%8.3f +/- %6.3f"
#.........这里部分代码省略.........
示例10: systematics
# 需要导入模块: from myutils import BetterConfigParser [as 别名]
# 或者: from myutils.BetterConfigParser import read [as 别名]
help="configuration tag")
parser.add_option("-t","--trainingRegions", dest="trainingRegions", default='',
help="cut region identifier")
parser.add_option("-S","--systematics", dest="systematics", default=2,
help="include systematics (0 for none, 1 for bdtVars, 2 for all (with btagWeights)")
parser.add_option("-x", "--test", dest="test", action="store_true", help="for debugging only!!!", default=False)
(opts, args) = parser.parse_args(argv)
if opts.config =="":
opts.config = ["config"]
# Import after configure to get help message
from myutils import BetterConfigParser, mvainfo, ParseInfo
if len(opts.tag.strip()) > 1:
config = BetterConfigParser()
config.read("{tag}config/paths.ini".format(tag=opts.tag))
configFiles = config.get("Configuration", "List").split(' ')
opts.config = ["{tag}config/{file}".format(tag=opts.tag, file=x.strip()) for x in configFiles]
print("reading config files:", opts.config)
sys = False
btagSys = False
if int(opts.systematics) > 0:
sys = True
if int(opts.systematics) > 1:
btagSys = True
# load config
config = BetterConfigParser()
config.read(opts.config)
converter = SampleTreesToNumpyConverter(config, opts.trainingRegions, useSyst=sys, useWeightSyst=btagSys, testRun=opts.test)
success = converter.run()
示例11: getEventCount
# 需要导入模块: from myutils import BetterConfigParser [as 别名]
# 或者: from myutils.BetterConfigParser import read [as 别名]
def getEventCount(config, sampleIdentifier, cut="1", sampleTree=None):
if not sampleTree:
sampleTree = SampleTree({'name': sampleIdentifier, 'folder': config.get('Directories',args.fromFolder).strip()}, config=config)
h1 = ROOT.TH1D("h1","h1",1,0,2)
nEvents = sampleTree.tree.Draw("1>>h1", "(" + cut + ")*genWeight")
nEventsWeighted = h1.GetBinContent(1)
h1.Delete()
return nEventsWeighted
# load config
config = BetterConfigParser()
configFolder = args.tag + 'config/'
print "config folder:", configFolder
config.read(configFolder + '/paths.ini')
configFiles = [x for x in config.get('Configuration','List').strip().split(' ') if len(x.strip()) > 0]
config = BetterConfigParser()
for configFile in configFiles:
config.read(configFolder + configFile)
print "read config ", configFile
pruneThreshold = float(args.prune)
sampleGroups = []
for x in args.samples.split(','):
sampleGroups.append(x.split('+'))
sampleCuts = args.cuts.strip().split(',')
if args.fc != '':
cutGroups = [x.strip(',').split(',') for x in args.fc.strip(';').split(';')]
示例12: __init__
# 需要导入模块: from myutils import BetterConfigParser [as 别名]
# 或者: from myutils.BetterConfigParser import read [as 别名]
class XbbRun:
def __init__(self, opts):
# get file list
self.filelist = FileList.decompress(opts.fileList) if len(opts.fileList) > 0 else None
print "len(filelist)",len(self.filelist),
if len(self.filelist) > 0:
print "filelist[0]:", self.filelist[0]
else:
print ''
# config
self.debug = 'XBBDEBUG' in os.environ
self.verifyCopy = True
self.opts = opts
self.config = BetterConfigParser()
self.config.read(opts.config)
samplesinfo = self.config.get('Directories', 'samplesinfo')
self.channel = self.config.get('Configuration', 'channel')
# load namespace, TODO
VHbbNameSpace = self.config.get('VHbbNameSpace', 'library')
ROOT.gSystem.Load(VHbbNameSpace)
# directories
self.pathIN = self.config.get('Directories', opts.inputDir)
self.pathOUT = self.config.get('Directories', opts.outputDir)
self.tmpDir = self.config.get('Directories', 'scratch')
print 'INput samples:\t%s'%self.pathIN
print 'OUTput samples:\t%s'%self.pathOUT
self.fileLocator = FileLocator(config=self.config)
# check if given sample identifier uniquely matches a samples from config
matchingSamples = ParseInfo(samplesinfo, self.pathIN).find(identifier=opts.sampleIdentifier)
if len(matchingSamples) != 1:
print "ERROR: need exactly 1 sample identifier as input with -S !!"
print matchingSamples
exit(1)
self.sample = matchingSamples[0]
# collections
self.collections = [x.strip() for x in opts.addCollections.split(',') if len(x.strip()) > 0] if len(opts.addCollections.strip())>0 else []
if len(self.collections) < 1:
print "\x1b[31mWARNING: no collections added! Specify the collections to add with the --addCollections option!\x1b[0m"
print 'collections to add:', self.collections
self.collections = self.parseCollectionList(self.collections)
print 'after parsing:', self.collections
# temorary folder to save the files of this job on the scratch
temporaryName = self.sample.identifier + '/' + uuid.uuid4().hex
# input files
self.subJobs = []
if opts.join:
print("INFO: join input files! This is an experimental feature!")
# translate naming convention of .txt file to imported files after the prep step
inputFileNamesAfterPrep = [self.fileLocator.getFilenameAfterPrep(x) for x in self.filelist]
self.subJobs.append({
'inputFileNames': self.filelist,
'localInputFileNames': ["{path}/{subfolder}/{filename}".format(path=self.pathIN, subfolder=self.sample.identifier, filename=localFileName) for localFileName in inputFileNamesAfterPrep],
'outputFileName': "{path}/{subfolder}/{filename}".format(path=self.pathOUT, subfolder=self.sample.identifier, filename=inputFileNamesAfterPrep[0]),
'tmpFileName': "{path}/{subfolder}/{filename}".format(path=self.tmpDir, subfolder=temporaryName, filename=inputFileNamesAfterPrep[0]),
})
else:
# create separate subjob for all files (default!)
for inputFileName in self.filelist:
inputFileNamesAfterPrep = [self.fileLocator.getFilenameAfterPrep(inputFileName)]
self.subJobs.append({
'inputFileNames': [inputFileName],
'localInputFileNames': ["{path}/{subfolder}/{filename}".format(path=self.pathIN, subfolder=self.sample.identifier, filename=localFileName) for localFileName in inputFileNamesAfterPrep],
'outputFileName': "{path}/{subfolder}/{filename}".format(path=self.pathOUT, subfolder=self.sample.identifier, filename=inputFileNamesAfterPrep[0]),
'tmpFileName': "{path}/{subfolder}/{filename}".format(path=self.tmpDir, subfolder=temporaryName, filename=inputFileNamesAfterPrep[0]),
})
# lists of single modules can be given instead of a module, "--addCollections Sys.all"
# [Sys]
# all = ['Sys.Vtype', 'Sys.Leptons', ...]
# TODO: make it fully recursive
def parseCollectionList(self, collections):
collectionsListsReplaced = []
for collection in collections:
if '.' in collection:
section = collection.split('.')[0]
key = collection.split('.')[1]
listExpression = self.config.get(section, key).strip()
if listExpression.startswith('[') and listExpression.endswith(']'):
listParsed = eval(listExpression)
for i in listParsed:
collectionsListsReplaced.append(i)
else:
collectionsListsReplaced.append(collection)
else:
collectionsListsReplaced.append(collection)
#.........这里部分代码省略.........
示例13: BetterConfigParser
# 需要导入模块: from myutils import BetterConfigParser [as 别名]
# 或者: from myutils.BetterConfigParser import read [as 别名]
#!/usr/bin/env python
from __future__ import print_function
import sys, ROOT, warnings
ROOT.gROOT.SetBatch(True)
#suppres the EvalInstace conversion warning bug
warnings.filterwarnings( action='ignore', category=RuntimeWarning, message='creating converter.*' )
from optparse import OptionParser
from myutils import BetterConfigParser, mvainfo, ParseInfo
#paths.ini general.ini cuts.ini training.ini datacards.ini plots.ini lhe_weights.ini samples_nosplit.ini
# load config
config = BetterConfigParser()
config.read('/mnt/t3nfs01/data01/shome/berger_p2/VHbb/CMSSW_9_4_0_pre3/src/Xbb/python/Zll2016config/paths.ini')
config.read('/mnt/t3nfs01/data01/shome/berger_p2/VHbb/CMSSW_9_4_0_pre3/src/Xbb/python/Zll2016config/general.ini')
config.read('/mnt/t3nfs01/data01/shome/berger_p2/VHbb/CMSSW_9_4_0_pre3/src/Xbb/python/Zll2016config/cuts.ini')
config.read('/mnt/t3nfs01/data01/shome/berger_p2/VHbb/CMSSW_9_4_0_pre3/src/Xbb/python/Zll2016config/training.ini')
config.read('/mnt/t3nfs01/data01/shome/berger_p2/VHbb/CMSSW_9_4_0_pre3/src/Xbb/python/Zll2016config/datacards.ini')
config.read('/mnt/t3nfs01/data01/shome/berger_p2/VHbb/CMSSW_9_4_0_pre3/src/Xbb/python/Zll2016config/plots.ini')
config.read('/mnt/t3nfs01/data01/shome/berger_p2/VHbb/CMSSW_9_4_0_pre3/src/Xbb/python/Zll2016config/lhe_weights.ini')
config.read('/mnt/t3nfs01/data01/shome/berger_p2/VHbb/CMSSW_9_4_0_pre3/src/Xbb/python/Zll2016config/samples_nosplit.ini')
print(config)
print(config.sections())
print(config.get('DYJetsToLL_M-50_HT-200to400_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_ext1', 'specialweight'))