CMS 3D CMS Logo

Functions
tools Namespace Reference

Functions

def addCrabInputFile (crabCfg, inputFile)
 
def check_proxy ()
 
def compute_product_string (product_string)
 
def copyFilesFromCastor (castor_dir, output_dir, type='root')
 
def copyFilesLocal (dir, output_dir, type='root')
 
def create_single_iov_db (inputs, run_number, output_db)
 
def dqmWorkflowName (datasetpath, type, rev=1)
 
def get_iovs (db, tag)
 
def get_process_object (cfg)
 
def get_tags (global_tag, records)
 
def getDatasetStr (datasetpath)
 
def haddInCastor (castor_dir, result_file, type='root', prefix='rfio:', suffix=None)
 
def haddLocal (dir, result_file, type='root')
 
def listFilesInCastor (castor_dir, type='root', prefix='rfio:')
 
def listFilesLocal (dir, type='root')
 
def loadCmsProcess (psetPath)
 
def loadCmsProcessFile (psetName)
 
def loadCrabCfg (cfgName=None)
 
def loadCrabDefault (crabCfg, config)
 
def make_unique_runranges (ali_producer)
 
def parseInput (inputFields, requiredFields=())
 
def prependPaths (process, seqname)
 
def remove_existing_object (path)
 
def replace_factors (product_string, name, value)
 
def replaceTemplate (template, opts)
 
def run_checked (cmd, suppress_stderr=False)
 
def setGridEnv (cmssw_dir)
 
def writeCfg (process, dir, psetName)
 
def writeCfgPkl (process, dir, psetName)
 

Function Documentation

def tools.addCrabInputFile (   crabCfg,
  inputFile 
)

Definition at line 183 of file tools.py.

Referenced by DTDQMValidation.DTDQMValidation.initCrab(), DTAnalysisResiduals.DTAnalysisResiduals.initCrab(), DTTTrigValid.DTTTrigValid.initCrab(), DTResidualCalibration.DTResidualCalibration.initCrab(), DTVDriftSegmentCalibration.DTVDriftSegmentCalibration.initCrab(), and DTVDriftMeanTimerCalibration.DTVDriftMeanTimerCalibration.initCrab().

183 def addCrabInputFile(crabCfg,inputFile):
184  additionalInputFiles = ''
185  if crabCfg.has_option('USER','additional_input_files'):
186  additionalInputFiles = crabCfg.get('USER','additional_input_files')
187 
188  if additionalInputFiles: additionalInputFiles += ',%s' % inputFile
189  else: additionalInputFiles = inputFile
190 
191  crabCfg.set('USER','additional_input_files',additionalInputFiles)
192 
193  return crabCfg
194 
def addCrabInputFile(crabCfg, inputFile)
Definition: tools.py:183
def tools.check_proxy ( )
Check if GRID proxy has been initialized.

Definition at line 217 of file tools.py.

218  """Check if GRID proxy has been initialized."""
219 
220  try:
221  with open(os.devnull, "w") as dump:
222  subprocess.check_call(["voms-proxy-info", "--exists"],
223  stdout = dump, stderr = dump)
224  except subprocess.CalledProcessError:
225  return False
226  return True
227 
228 
def check_proxy()
Definition: tools.py:217
def tools.compute_product_string (   product_string)
Takes `product_string` and returns the product of the factors as string.

Arguments:
- `product_string`: string containing product ('<factor>*<factor>*...')

Definition at line 206 of file tools.py.

References objects.autophobj.float, and harvestTrackValidationPlots.str.

206 def compute_product_string(product_string):
207  """Takes `product_string` and returns the product of the factors as string.
208 
209  Arguments:
210  - `product_string`: string containing product ('<factor>*<factor>*...')
211  """
212 
213  factors = [float(f) for f in product_string.split("*")]
214  return str(reduce(lambda x,y: x*y, factors))
215 
216 
def compute_product_string(product_string)
Definition: tools.py:206
def tools.copyFilesFromCastor (   castor_dir,
  output_dir,
  type = 'root' 
)

Definition at line 55 of file tools.py.

References listFilesInCastor().

Referenced by DTCalibrationWorker.DTCalibrationWorker.runNoiseWorkflow().

55 def copyFilesFromCastor(castor_dir,output_dir,type='root'):
56  from subprocess import call
57  files = listFilesInCastor(castor_dir,type,'')
58 
59  print "Copying files from %s to %s" % (castor_dir,output_dir)
60  for item in files:
61  cmd = ['rfcp',item,output_dir]
62  print "..." + item
63  retcode = call(cmd)
64  if retcode != 0: raise RuntimeError('Error in copying file %s to directory %s' % (item,output_dir))
65 
66  return 0
67 
def listFilesInCastor(castor_dir, type='root', prefix='rfio:')
Definition: tools.py:30
def copyFilesFromCastor(castor_dir, output_dir, type='root')
Definition: tools.py:55
def tools.copyFilesLocal (   dir,
  output_dir,
  type = 'root' 
)

Definition at line 68 of file tools.py.

References listFilesLocal().

Referenced by DTCalibrationWorker.DTCalibrationWorker.runNoiseWorkflow().

68 def copyFilesLocal(dir,output_dir,type='root'):
69  if not dir: raise ValueError('Please specify valid dir')
70  if not output_dir: raise ValueError('Please specify valid output dir')
71 
72  from subprocess import call
73  files = listFilesLocal(dir,type)
74  cmd = ['cp']
75  cmd.extend(files)
76  cmd.append(output_dir)
77  print cmd
78  retcode = call(cmd)
79  return retcode
80 
def copyFilesLocal(dir, output_dir, type='root')
Definition: tools.py:68
def listFilesLocal(dir, type='root')
Definition: tools.py:42
def tools.create_single_iov_db (   inputs,
  run_number,
  output_db 
)
Create an sqlite file with single-IOV tags for alignment payloads.

Arguments:
- `inputs`: dictionary with input needed for payload extraction
- `run_number`: run for which the IOVs are selected
- `output_db`: name of the output sqlite file

Definition at line 11 of file tools.py.

References join(), remove_existing_object(), run_checked(), and harvestTrackValidationPlots.str.

11 def create_single_iov_db(inputs, run_number, output_db):
12  """Create an sqlite file with single-IOV tags for alignment payloads.
13 
14  Arguments:
15  - `inputs`: dictionary with input needed for payload extraction
16  - `run_number`: run for which the IOVs are selected
17  - `output_db`: name of the output sqlite file
18  """
19 
20  # find the IOV containing `run_number`
21  for record,tag in inputs.iteritems():
22  run_is_covered = False
23  for iov in reversed(tag["iovs"]):
24  if iov <= run_number:
25  tag["since"] = str(iov)
26  run_is_covered = True
27  break
28  if not run_is_covered:
29  msg = ("Run number {0:d} is not covered in '{1:s}' ({2:s}) from"
30  " '{3:s}'.".format(run_number, tag["tag"], record,
31  global_tag))
32  print msg
33  print "Aborting..."
34  sys.exit(1)
35 
36  result = {}
37  remove_existing_object(output_db)
38 
39  for record,tag in inputs.iteritems():
40  result[record] = {"connect": "sqlite_file:"+output_db,
41  "tag": "_".join([tag["tag"], tag["since"]])}
42 
43  if tag["connect"] == "pro":
44  source_connect = "frontier://FrontierProd/CMS_CONDITIONS"
45  elif tag["connect"] == "dev":
46  source_connect = "frontier://FrontierPrep/CMS_CONDITIONS"
47  else:
48  source_connect = tag["connect"]
49 
50  cmd = ("conddb_import",
51  "-f", source_connect,
52  "-c", result[record]["connect"],
53  "-i", tag["tag"],
54  "-t", result[record]["tag"],
55  "-b", str(run_number),
56  "-e", str(run_number))
57  run_checked(cmd)
58  if len(inputs) > 0:
59  run_checked(["sqlite3", output_db, "update iov set since=1"])
60 
61  return result
62 
63 
def remove_existing_object(path)
Definition: tools.py:229
def create_single_iov_db(inputs, run_number, output_db)
Definition: tools.py:11
def run_checked(cmd, suppress_stderr=False)
Definition: tools.py:64
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def tools.dqmWorkflowName (   datasetpath,
  type,
  rev = 1 
)

Definition at line 23 of file tools.py.

Referenced by DTDqm.DTDqm.initProcess(), and DTDQMHarvesting.DTDQMHarvesting.initProcess().

23 def dqmWorkflowName(datasetpath,type,rev=1):
24  workflowName = datasetpath
25  sections = workflowName.split('/')[1:]
26  workflowName = '/%s/%s-%s-rev%d/%s' % (sections[0],sections[1],type,rev,sections[2])
27 
28  return workflowName
29 
def dqmWorkflowName(datasetpath, type, rev=1)
Definition: tools.py:23
def tools.get_iovs (   db,
  tag 
)
Retrieve the list of IOVs from `db` for `tag`.

Arguments:
- `db`: database connection string
- `tag`: tag of database record

Definition at line 164 of file tools.py.

References Vispa.Plugins.EdmBrowser.EdmDataAccessor.all(), ALCARECOTkAlBeamHalo_cff.filter, createfilelist.int, and python.rootplot.root2matplotlib.replace().

164 def get_iovs(db, tag):
165  """Retrieve the list of IOVs from `db` for `tag`.
166 
167  Arguments:
168  - `db`: database connection string
169  - `tag`: tag of database record
170  """
171 
172  db = db.replace("sqlite_file:", "").replace("sqlite:", "")
173  db = db.replace("frontier://FrontierProd/CMS_CONDITIONS", "pro")
174  db = db.replace("frontier://FrontierPrep/CMS_CONDITIONS", "dev")
175 
176  con = conddb.connect(url = conddb.make_url(db))
177  session = con.session()
178  IOV = session.get_dbtype(conddb.IOV)
179 
180  iovs = set(session.query(IOV.since).filter(IOV.tag_name == tag).all())
181  if len(iovs) == 0:
182  print "No IOVs found for tag '"+tag+"' in database '"+db+"'."
183  sys.exit(1)
184 
185  session.close()
186 
187  return sorted([int(item[0]) for item in iovs])
188 
189 
def replace(string, replacements)
def get_iovs(db, tag)
Definition: tools.py:164
def tools.get_process_object (   cfg)
Returns cms.Process object defined in `cfg`.

Arguments:
- `cfg`: path to CMSSW config file

Definition at line 84 of file tools.py.

85  """Returns cms.Process object defined in `cfg`.
86 
87  Arguments:
88  - `cfg`: path to CMSSW config file
89  """
90 
91  sys.path.append(os.path.dirname(cfg)) # add location to python path
92  cache_stdout = sys.stdout
93  sys.stdout = open(os.devnull, "w") # suppress unwanted output
94  try:
95  __configuration = \
96  importlib.import_module(os.path.splitext(os.path.basename(cfg))[0])
97  except Exception as e:
98  print "Problem detected in configuration file '{0}'.".format(cfg)
99  raise e
100  sys.stdout = cache_stdout
101  sys.path.pop() # clean up python path again
102  try:
103  os.remove(cfg+"c") # try to remove temporary .pyc file
104  except OSError as e:
105  if e.args == (2, "No such file or directory"): pass
106  else: raise
107 
108  return __configuration.process
109 
110 
def get_process_object(cfg)
Definition: tools.py:84
def tools.get_tags (   global_tag,
  records 
)
Get tags for `records` contained in `global_tag`.

Arguments:
- `global_tag`: global tag of interest
- `records`: database records of interest

Definition at line 129 of file tools.py.

References Vispa.Plugins.EdmBrowser.EdmDataAccessor.all(), and ALCARECOTkAlBeamHalo_cff.filter.

129 def get_tags(global_tag, records):
130  """Get tags for `records` contained in `global_tag`.
131 
132  Arguments:
133  - `global_tag`: global tag of interest
134  - `records`: database records of interest
135  """
136 
137  if len(records) == 0: return {} # avoid useless DB query
138 
139  # check for auto GT
140  if global_tag.startswith("auto:"):
141  import Configuration.AlCa.autoCond as AC
142  try:
143  global_tag = AC.autoCond[global_tag.split("auto:")[-1]]
144  except KeyError:
145  print "Unsupported auto GT:", global_tag
146  sys.exit(1)
147 
148  # setting up the DB session
149  con = conddb.connect(url = conddb.make_url())
150  session = con.session()
151  GlobalTagMap = session.get_dbtype(conddb.GlobalTagMap)
152 
153  # query tag names for records of interest contained in `global_tag`
154  tags = session.query(GlobalTagMap.record, GlobalTagMap.tag_name).\
155  filter(GlobalTagMap.global_tag_name == global_tag,
156  GlobalTagMap.record.in_(records)).all()
157 
158  # closing the DB session
159  session.close()
160 
161  return {item[0]: {"tag": item[1], "connect": "pro"} for item in tags}
162 
163 
def get_tags(global_tag, records)
Definition: tools.py:129
def tools.getDatasetStr (   datasetpath)
def tools.haddInCastor (   castor_dir,
  result_file,
  type = 'root',
  prefix = 'rfio:',
  suffix = None 
)

Definition at line 81 of file tools.py.

References listFilesInCastor().

Referenced by DTCalibrationWorker.DTCalibrationWorker.runAnalysisResiduals(), DTCalibrationWorker.DTCalibrationWorker.runResidualCalib(), DTCalibrationWorker.DTCalibrationWorker.runTtrigProd(), DTCalibrationWorker.DTCalibrationWorker.runVDriftMeanTimerCalib(), and DTCalibrationWorker.DTCalibrationWorker.runVDriftSegmentCalib().

81 def haddInCastor(castor_dir,result_file,type = 'root',prefix = 'rfio:',suffix = None):
82  if not castor_dir: raise ValueError('Please specify valid castor dir')
83  if not result_file: raise ValueError('Please specify valid output file name')
84 
85  #cmd = 'hadd %s `./listfilesCastor %s | grep %s`'%(result_file,castor_dir,type)
86  #print "Running",cmd
87  #os.system(cmd)
88  from subprocess import call
89  files = listFilesInCastor(castor_dir,type,prefix)
90  if suffix: files = [item + suffix for item in files]
91 
92  cmd = ['hadd',result_file]
93  cmd.extend(files)
94  #print cmd
95  retcode = call(cmd)
96  return retcode
97 
def listFilesInCastor(castor_dir, type='root', prefix='rfio:')
Definition: tools.py:30
def haddInCastor(castor_dir, result_file, type='root', prefix='rfio:', suffix=None)
Definition: tools.py:81
def tools.haddLocal (   dir,
  result_file,
  type = 'root' 
)

Definition at line 98 of file tools.py.

References listFilesLocal().

Referenced by DTCalibrationWorker.DTCalibrationWorker.runAnalysisResiduals(), DTCalibrationWorker.DTCalibrationWorker.runResidualCalib(), DTCalibrationWorker.DTCalibrationWorker.runTtrigProd(), DTCalibrationWorker.DTCalibrationWorker.runVDriftMeanTimerCalib(), and DTCalibrationWorker.DTCalibrationWorker.runVDriftSegmentCalib().

98 def haddLocal(dir,result_file,type = 'root'):
99  if not dir: raise ValueError('Please specify valid dir')
100  if not result_file: raise ValueError('Please specify valid output file name')
101 
102  from subprocess import call
103  files = listFilesLocal(dir,type)
104  cmd = ['hadd',result_file]
105  cmd.extend(files)
106  #print cmd
107  retcode = call(cmd)
108  return retcode
109 
def haddLocal(dir, result_file, type='root')
Definition: tools.py:98
def listFilesLocal(dir, type='root')
Definition: tools.py:42
def tools.listFilesInCastor (   castor_dir,
  type = 'root',
  prefix = 'rfio:' 
)

Definition at line 30 of file tools.py.

Referenced by copyFilesFromCastor(), haddInCastor(), DTDqm.runDQM(), DTDQMMerge.runDQM(), DTCalibrationWorker.DTCalibrationWorker.runDQMClient(), DTCalibrationWorker.DTCalibrationWorker.runDQMHarvesting(), and DTCalibrationWorker.DTCalibrationWorker.runDQMMerge().

30 def listFilesInCastor(castor_dir,type = 'root',prefix = 'rfio:'):
31  if not castor_dir: raise ValueError('Please specify valid castor dir')
32 
33  from subprocess import Popen,PIPE
34  p1 = Popen(['nsls',castor_dir],stdout=PIPE)
35  #p2 = Popen(['grep',type],stdin=p1.stdout,stdout=PIPE)
36  #files = [prefix + castor_dir + "/" + item[:-1] for item in p2.stdout]
37  #p2.stdout.close()
38  files = [ "%s%s/%s" % (prefix,castor_dir,item.rstrip()) for item in p1.stdout if item.find(type) != -1 ]
39  p1.stdout.close()
40  return files
41 
def listFilesInCastor(castor_dir, type='root', prefix='rfio:')
Definition: tools.py:30
def tools.listFilesLocal (   dir,
  type = 'root' 
)

Definition at line 42 of file tools.py.

Referenced by copyFilesLocal(), haddLocal(), DTCalibrationWorker.DTCalibrationWorker.runDQMClient(), DTCalibrationWorker.DTCalibrationWorker.runDQMHarvesting(), and DTCalibrationWorker.DTCalibrationWorker.runDQMMerge().

42 def listFilesLocal(dir,type = 'root'):
43  if not dir: raise ValueError('Please specify valid dir')
44 
45  #from subprocess import Popen,PIPE
46  #p1 = Popen(['ls',dir],stdout=PIPE)
47  #p2 = Popen(['grep',type],stdin=p1.stdout,stdout=PIPE)
48  #files = [dir + "/" + item[:-1] for item in p2.stdout]
49  #p2.stdout.close()
50  files = os.listdir(dir)
51  files = [ "%s/%s" % (dir,item) for item in files if item.find(type) != -1 ]
52 
53  return files
54 
def listFilesLocal(dir, type='root')
Definition: tools.py:42
def tools.loadCmsProcess (   psetPath)
def tools.loadCmsProcessFile (   psetName)

Definition at line 140 of file tools.py.

140 def loadCmsProcessFile(psetName):
141  pset = imp.load_source("psetmodule",psetName)
142  return pset.process
143 
def loadCmsProcessFile(psetName)
Definition: tools.py:140
def tools.loadCrabCfg (   cfgName = None)
def tools.loadCrabDefault (   crabCfg,
  config 
)

Definition at line 195 of file tools.py.

Referenced by DTNoiseCalibration.DTNoiseCalibration.initCrab(), DTTTrigProd.DTTTrigProd.initCrab(), DTDQMValidation.DTDQMValidation.initCrab(), DTResidualCalibration.DTResidualCalibration.initCrab(), DTAnalysisResiduals.DTAnalysisResiduals.initCrab(), DTTTrigValid.DTTTrigValid.initCrab(), DTVDriftSegmentCalibration.DTVDriftSegmentCalibration.initCrab(), and DTVDriftMeanTimerCalibration.DTVDriftMeanTimerCalibration.initCrab().

195 def loadCrabDefault(crabCfg,config):
196  # CRAB section
197  if not crabCfg.has_section('CRAB'): crabCfg.add_section('CRAB')
198  crabCfg.set('CRAB','jobtype','cmssw')
199 
200  if hasattr(config,'scheduler') and config.scheduler: crabCfg.set('CRAB','scheduler',config.scheduler)
201  else: crabCfg.set('CRAB','scheduler','CAF')
202 
203  if hasattr(config,'useserver') and config.useserver: crabCfg.set('CRAB','use_server',1)
204 
205  # CMSSW section
206  if not crabCfg.has_section('CMSSW'): crabCfg.add_section('CMSSW')
207  if hasattr(config,'datasetpath') and config.datasetpath: crabCfg.set('CMSSW','datasetpath',config.datasetpath)
208  else: crabCfg.set('CMSSW','datasetpath','/XXX/YYY/ZZZ')
209  crabCfg.set('CMSSW','pset','pset.py')
210 
211  # Splitting config
212  crabCfg.remove_option('CMSSW','total_number_of_events')
213  crabCfg.remove_option('CMSSW','events_per_job')
214  crabCfg.remove_option('CMSSW','number_of_jobs')
215  crabCfg.remove_option('CMSSW','total_number_of_lumis')
216  crabCfg.remove_option('CMSSW','lumis_per_job')
217  crabCfg.remove_option('CMSSW','lumi_mask')
218  crabCfg.remove_option('CMSSW','split_by_run')
219 
220  """
221  if hasattr(config,'totalnumberevents'): crabCfg.set('CMSSW','total_number_of_events',config.totalnumberevents)
222  if hasattr(config,'eventsperjob'): crabCfg.set('CMSSW','events_per_job',config.eventsperjob)
223  """
224  if hasattr(config,'splitByLumi') and config.splitByLumi:
225  crabCfg.set('CMSSW','total_number_of_lumis',config.totalnumberlumis)
226  crabCfg.set('CMSSW','lumis_per_job',config.lumisperjob)
227  if hasattr(config,'lumimask') and config.lumimask: crabCfg.set('CMSSW','lumi_mask',config.lumimask)
228  elif hasattr(config,'splitByEvent') and config.splitByEvent:
229  crabCfg.set('CMSSW','total_number_of_events',config.totalnumberevents)
230  crabCfg.set('CMSSW','events_per_job',config.eventsperjob)
231  else:
232  crabCfg.set('CMSSW','split_by_run',1)
233 
234  if hasattr(config,'splitByEvent') and config.splitByEvent:
235  crabCfg.remove_option('CMSSW','runselection')
236  else:
237  if hasattr(config,'runselection') and config.runselection:
238  crabCfg.set('CMSSW','runselection',config.runselection)
239 
240  # USER section
241  if not crabCfg.has_section('USER'): crabCfg.add_section('USER')
242 
243  # Stageout config
244  if hasattr(config,'stageOutCAF') and config.stageOutCAF:
245  crabCfg.set('USER','return_data',0)
246  crabCfg.set('USER','copy_data',1)
247  crabCfg.set('USER','storage_element','T2_CH_CAF')
248  crabCfg.set('USER','user_remote_dir',config.userdircaf)
249  crabCfg.set('USER','check_user_remote_dir',0)
250  elif hasattr(config,'stageOutLocal') and config.stageOutLocal:
251  crabCfg.set('USER','return_data',1)
252  crabCfg.set('USER','copy_data',0)
253  crabCfg.remove_option('USER','storage_element')
254  crabCfg.remove_option('USER','user_remote_dir')
255  crabCfg.remove_option('USER','check_user_remote_dir')
256 
257  if hasattr(config,'email') and config.email: crabCfg.set('USER','eMail',config.email)
258  crabCfg.set('USER','xml_report','crabReport.xml')
259 
260  if hasattr(config,'runOnGrid') and config.runOnGrid:
261  crabCfg.remove_section('CAF')
262  if hasattr(config,'ce_black_list'):
263  if not crabCfg.has_section('GRID'): crabCfg.add_section('GRID')
264  crabCfg.set('GRID','ce_black_list', config.ce_black_list)
265  if hasattr(config,'ce_white_list'):
266  if not crabCfg.has_section('GRID'): crabCfg.add_section('GRID')
267  crabCfg.set('GRID','ce_white_list', config.ce_white_list)
268  else:
269  if not crabCfg.has_section('CAF'): crabCfg.add_section('CAF')
270  crabCfg.set('CAF','queue',config.queueAtCAF)
271 
272  return crabCfg
273 
def loadCrabDefault(crabCfg, config)
Definition: tools.py:195
def tools.make_unique_runranges (   ali_producer)
Derive unique run ranges from AlignmentProducer PSet.

Arguments:
- `ali_producer`: cms.PSet containing AlignmentProducer configuration

Definition at line 111 of file tools.py.

References createfilelist.int.

111 def make_unique_runranges(ali_producer):
112  """Derive unique run ranges from AlignmentProducer PSet.
113 
114  Arguments:
115  - `ali_producer`: cms.PSet containing AlignmentProducer configuration
116  """
117 
118  if (hasattr(ali_producer, "RunRangeSelection") and
119  len(ali_producer.RunRangeSelection) > 0):
120  iovs = set([int(iov)
121  for sel in ali_producer.RunRangeSelection
122  for iov in sel.RunRanges])
123  if len(iovs) == 0: return [1] # single IOV starting from run 1
124  return sorted(iovs)
125  else:
126  return [1] # single IOV starting from run 1
127 
128 
def make_unique_runranges(ali_producer)
Definition: tools.py:111
def tools.parseInput (   inputFields,
  requiredFields = () 
)

Definition at line 122 of file tools.py.

Referenced by edmStreamStallGrapher.readLogFile().

122 def parseInput(inputFields,requiredFields = ()):
123 
124  class options: pass
125  for item in sys.argv:
126  option = item.split('=')[0]
127  if option in inputFields:
128  value = item.split('=')[1]
129  if value in ('true','True','yes','Yes'): value = True
130  elif value in ('false','False','no','No'): value = False
131 
132  setattr(options,option,value)
133 
134  for item in requiredFields:
135  if not hasattr(options,item):
136  raise RuntimeError('Need to set "%s"' % item)
137 
138  return options
139 
def parseInput(inputFields, requiredFields=())
Definition: tools.py:122
def tools.remove_existing_object (   path)
Tries to remove file or directory located at `path`. If the user
has no delete permissions, the object is moved to a backup
file. If this fails it tries 5 times in total and then asks to
perform a cleanup by a user with delete permissions.

Arguments:
- `name`: name of the object to be (re)moved

Definition at line 229 of file tools.py.

Referenced by create_single_iov_db().

230  """
231  Tries to remove file or directory located at `path`. If the user
232  has no delete permissions, the object is moved to a backup
233  file. If this fails it tries 5 times in total and then asks to
234  perform a cleanup by a user with delete permissions.
235 
236  Arguments:
237  - `name`: name of the object to be (re)moved
238  """
239 
240  if os.path.exists(path):
241  remove_method = shutil.rmtree if os.path.isdir(path) else os.remove
242  move_method = shutil.move if os.path.isdir(path) else os.rename
243  try:
244  remove_method(path)
245  except OSError as e:
246  if e.args != (13, "Permission denied"): raise
247  backup_path = path.rstrip("/")+"~"
248  for _ in xrange(5):
249  try:
250  if os.path.exists(backup_path): remove_method(backup_path)
251  move_method(path, backup_path)
252  break
253  except OSError as e:
254  if e.args != (13, "Permission denied"): raise
255  backup_path += "~"
256  if os.path.exists(path):
257  msg = ("Cannot remove '{}' due to missing 'delete' ".format(path)
258  +"permissions and the limit of 5 backups is reached. Please "
259  "ask a user with 'delete' permissions to clean up.")
260  print msg
261  sys.exit(1)
262 
def remove_existing_object(path)
Definition: tools.py:229
def tools.replace_factors (   product_string,
  name,
  value 
)
Takes a `product_string` and replaces all factors with `name` by `value`.

Arguments:
- `product_string`: input string containing a product
- `name`: name of the factor
- `value`: value of the factor

Definition at line 190 of file tools.py.

References harvestTrackValidationPlots.str.

190 def replace_factors(product_string, name, value):
191  """Takes a `product_string` and replaces all factors with `name` by `value`.
192 
193  Arguments:
194  - `product_string`: input string containing a product
195  - `name`: name of the factor
196  - `value`: value of the factor
197  """
198 
199  value = str(value) # ensure it's a string
200  return re.sub(r"^"+name+r"$", value, # single factor
201  re.sub(r"[*]"+name+r"$", r"*"+value, # rhs
202  re.sub(r"^"+name+r"[*]", value+r"*", # lhs
203  re.sub(r"[*]"+name+r"[*]", r"*"+value+r"*",
204  product_string))))
205 
def replace_factors(product_string, name, value)
Definition: tools.py:190
def tools.replaceTemplate (   template,
  opts 
)

Definition at line 5 of file tools.py.

References harvestTrackValidationPlots.str.

5 def replaceTemplate(template,**opts):
6  result = open(template).read()
7  for item in opts:
8  old = '@@%s@@'%item
9  new = str(opts[item])
10  print "Replacing",old,"to",new
11  result = result.replace(old,new)
12 
13  return result
14 
def replaceTemplate(template, opts)
Definition: tools.py:5
def tools.run_checked (   cmd,
  suppress_stderr = False 
)
Run `cmd` and exit in case of failures.

Arguments:
- `cmd`: list containing the strings of the command
- `suppress_stderr`: suppress output from stderr

Definition at line 64 of file tools.py.

References join().

Referenced by create_single_iov_db().

64 def run_checked(cmd, suppress_stderr = False):
65  """Run `cmd` and exit in case of failures.
66 
67  Arguments:
68  - `cmd`: list containing the strings of the command
69  - `suppress_stderr`: suppress output from stderr
70  """
71 
72  try:
73  with open(os.devnull, "w") as devnull:
74  if suppress_stderr:
75  subprocess.check_call(cmd, stdout = devnull, stderr = devnull)
76  else:
77  subprocess.check_call(cmd, stdout = devnull)
78  except subprocess.CalledProcessError as e:
79  print "Problem in running the following command:"
80  print " ".join(e.cmd)
81  sys.exit(1)
82 
83 
def run_checked(cmd, suppress_stderr=False)
Definition: tools.py:64
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def tools.setGridEnv (   cmssw_dir)

Definition at line 110 of file tools.py.

110 def setGridEnv(cmssw_dir):
111  cwd = os.getcwd()
112  os.chdir(cmssw_dir)
113 
114  os.system('source /afs/cern.ch/cms/LCG/LCG-2/UI/cms_ui_env.sh')
115  os.system('cmsenv')
116  os.system('source /afs/cern.ch/cms/ccs/wm/scripts/Crab/crab.sh')
117 
118  os.chdir(cwd)
119 
120  return
121 
def setGridEnv(cmssw_dir)
Definition: tools.py:110
def tools.writeCfg (   process,
  dir,
  psetName 
)

Definition at line 158 of file tools.py.

References TriggerAnalyzer.write().

158 def writeCfg(process,dir,psetName):
159  if not os.path.exists(dir): os.makedirs(dir)
160  open(dir + '/' + psetName,'w').write(process.dumpPython())
161 
def writeCfg(process, dir, psetName)
Definition: tools.py:158
def write(self, setup)
def tools.writeCfgPkl (   process,
  dir,
  psetName 
)

Definition at line 162 of file tools.py.

162 def writeCfgPkl(process,dir,psetName):
163  if not os.path.exists(dir): os.makedirs(dir)
164 
165  pklFileName = psetName.split('.')[0] + '.pkl'
166  pklFile = open(dir + '/' + pklFileName,"wb")
167  myPickle = pickle.Pickler(pklFile)
168  myPickle.dump(process)
169  pklFile.close()
170 
171  outFile = open(dir + '/' + psetName,"w")
172  outFile.write("import FWCore.ParameterSet.Config as cms\n")
173  outFile.write("import pickle\n")
174  outFile.write("process = pickle.load(open('%s', 'rb'))\n" % pklFileName)
175  outFile.close()
176 
177 
def writeCfgPkl(process, dir, psetName)
Definition: tools.py:162