CMS 3D CMS Logo

Classes | Functions | Variables
utils Namespace Reference

Classes

class  BinToBin
 
class  BinToBin1percent
 
class  Chi2
 
class  KS
 
class  StatisticalTest
 
class  unpickler
 

Functions

def ask_ok (prompt, retries=4, complaint='yes or no')
 
def code_generator (kwds)
 
def friendly_since (time_type, since)
 
def functor (code, kwds, debug=0)
 
def get_relval_cmssw_version (file)
 
def get_relval_id (file)
 
def get_relval_max_version (files)
 
def get_relval_version (file)
 -------------—— Make files pairs: RelVal utils ---------------—— More...
 
def get_relvaldata_cmssw_version (file)
 
def get_relvaldata_id (file)
 -----------—— Make files pairs: RelValData utils --------------—— More...
 
def get_relvaldata_max_version (files)
 
def get_relvaldata_version (file)
 
def getNbins (h)
 
def is_empty (h)
 
def is_relvaldata (files)
 ----------------------— Make files pairs -----------------------— More...
 
def is_sparse (h)
 
def literal2root (literal, rootType)
 
def logger (msg_level, message)
 
def make_files_pairs (files, verbose=True)
 
def parse_word (word)
 
def profile2histo (profile)
 
def setTDRStyle ()
 
def test_env (tdir, tmpl)
 
def to_datetime (date_string)
 
def to_timestamp (obj)
 
def tree (idir)
 
def user_info (ainput=None)
 
def wget (url)
 

Variables

 _log_level
 
 argv
 
 gErrorIgnoreLevel
 
 theargv
 

Detailed Description

File that contains utility functions used by various modules, but that do not fit into any single module.

Function Documentation

def utils.ask_ok (   prompt,
  retries = 4,
  complaint = 'yes or no' 
)

Definition at line 429 of file utils.py.

References edm.print().

429 def ask_ok(prompt, retries=4, complaint='yes or no'):
430  while True:
431  ok = raw_input(prompt)
432  if ok in ('y', 'ye', 'yes'):
433  return True
434  if ok in ('n', 'no'):
435  return False
436  retries = retries - 1
437  if retries < 0:
438  raise IOError('refusenik user')
439  print(complaint)
440 
441 #-------------------------------------------------------------------------------
442 
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def ask_ok(prompt, retries=4, complaint='yes or no')
Definition: utils.py:429
def utils.code_generator (   kwds)
Code generator function, parse user arguments, load and
return appropriate template generator module.

Definition at line 108 of file utils.py.

References edm.print(), and str.

Referenced by cms.generate(), and main.generator().

108 def code_generator(kwds):
109  """
110  Code generator function, parse user arguments, load and
111  return appropriate template generator module.
112  """
113  debug = kwds.get('debug', None)
114  if debug:
115  print("Configuration:")
116  pprint.pprint(kwds)
117  try:
118  klass = kwds.get('tmpl')
119  mname = 'FWCore.Skeletons.%s' % klass.lower()
120  module = __import__(mname, fromlist=[klass])
121  except ImportError as err:
122  klass = 'AbstractPkg'
123  module = __import__('FWCore.Skeletons.pkg', fromlist=[klass])
124  if debug:
125  print("%s, will use %s" % (str(err), klass))
126  obj = getattr(module, klass)(kwds)
127  return obj
128 
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def code_generator(kwds)
Definition: utils.py:108
#define str(s)
def utils.friendly_since (   time_type,
  since 
)
Takes a since and, if it is Run-based expressed as Lumi-based,
returns the run number.
Otherwise, returns the since without transformations.

Definition at line 18 of file utils.py.

18 def friendly_since(time_type, since):
19  """
20  Takes a since and, if it is Run-based expressed as Lumi-based,
21  returns the run number.
22  Otherwise, returns the since without transformations.
23  """
24  if time_type == "Run" and (since & 0xffffff) == 0:
25  return since >> 32
26  else:
27  return since
def friendly_since(time_type, since)
Definition: utils.py:18
def utils.functor (   code,
  kwds,
  debug = 0 
)
Auto-generate and execute function with given code and configuration
For details of compile/exec/eval see
http://lucumr.pocoo.org/2011/2/1/exec-in-python/

Definition at line 56 of file utils.py.

References join(), and edm.print().

Referenced by pkg.AbstractPkg.write().

56 def functor(code, kwds, debug=0):
57  """
58  Auto-generate and execute function with given code and configuration
59  For details of compile/exec/eval see
60  http://lucumr.pocoo.org/2011/2/1/exec-in-python/
61  """
62  args = []
63  for key, val in kwds.items():
64  if isinstance(val, str):
65  arg = '%s="%s"' % (key, val)
66  elif isinstance(val, list):
67  arg = '%s=%s' % (key, val)
68  else:
69  msg = 'Unsupported data type "%s" <%s>' % (val, type(val))
70  raise Exception(msg)
71  args.append(arg)
72  func = '\nimport sys'
73  func += '\nimport StringIO'
74  func += "\ndef func(%s):\n" % ','.join(args)
75  func += code
76  func += """
77 def capture():
78  "Capture snippet printous"
79  old_stdout = sys.stdout
80  sys.stdout = StringIO.StringIO()
81  func()
82  out = sys.stdout.getvalue()
83  sys.stdout = old_stdout
84  return out\n
85 capture()\n"""
86  if debug:
87  print("\n### generated code\n")
88  print(func)
89  # compile python code as exec statement
90  obj = compile(func, '<string>', 'exec')
91  # define execution namespace
92  namespace = {}
93  # execute compiled python code in given namespace
94  exec(obj, namespace)
95  # located generated function object, run it and return its results
96  return namespace['capture']()
97 
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def functor(code, kwds, debug=0)
Definition: utils.py:56
def utils.get_relval_cmssw_version (   file)

Definition at line 542 of file utils.py.

543  cmssw_release = re.findall('(CMSSW_\d*_\d*_\d*(?:_[\w\d]*)?)-', file)
544  gr_r_version = re.findall('CMSSW_\d*_\d*_\d*(?:_[\w\d]*)?-([\w\d]*)_V\d*\w?(_[\w\d]*)?-v', file)
545  if cmssw_release and gr_r_version:
546  if "PU" in gr_r_version[0][0] and not "FastSim" in file:
547  __gt = re.sub('^[^_]*_', "", gr_r_version[0][0])
548  __process_string = gr_r_version[0][1]
549  return (__gt, __process_string)
550  elif "PU" in gr_r_version[0][0] and "FastSim" in file: #a check for FastSimPU samples
551  return (cmssw_release[0], "PU_") #with possibly different GT's
552  return (cmssw_release[0], gr_r_version[0])
553 
def get_relval_cmssw_version(file)
Definition: utils.py:542
def utils.get_relval_id (   file)
Returns unique relval ID (dataset name) for a given file.

Definition at line 554 of file utils.py.

References edmIntegrityCheck.group.

554 def get_relval_id(file):
555  """Returns unique relval ID (dataset name) for a given file."""
556  dataset_name = re.findall('R\d{9}__([\w\D]*)__CMSSW_', file)
557  __process_string = re.search('CMSSW_\d*_\d*_\d*(?:_[\w\d]*)?-([\w\d]*)_V\d*\w?(_[\w\d]*)?-v', file)
558  _ps = ""
559  if __process_string:
560  if "PU" in __process_string.group(1) and not "FastSim" in file:
561  _ps = re.search('^[^_]*_', __process_string.group(1)).group()
562  elif "PU" in __process_string.group(1) and "FastSim" in file:
563  return dataset_name[0]+"_", _ps ##some testing is needed
564  return dataset_name[0], _ps
565 
def get_relval_id(file)
Definition: utils.py:554
def utils.get_relval_max_version (   files)
Returns file with maximum version at a) beggining of the file,
e.g. DQM_V000M b) at the end of run, e.g. _run2012-vM. M has to be max.

Definition at line 530 of file utils.py.

References get_relval_version().

531  """Returns file with maximum version at a) beggining of the file,
532  e.g. DQM_V000M b) at the end of run, e.g. _run2012-vM. M has to be max."""
533  max_file = files[0]
534  max_v = get_relval_version(files[0])
535  for file in files:
536  file_v = get_relval_version(file)
537  if file_v[1] > max_v[1] or ((file_v[1] == max_v[1]) and (file_v[0] > max_v[0])):
538  max_file = file
539  max_v = file_v
540  return max_file
541 
def get_relval_version(file)
-------------—— Make files pairs: RelVal utils ---------------——
Definition: utils.py:523
def get_relval_max_version(files)
Definition: utils.py:530
def utils.get_relval_version (   file)

-------------—— Make files pairs: RelVal utils ---------------——

Returns tuple (CMSSW version, run version) for specified file.

Definition at line 523 of file utils.py.

References createfilelist.int.

Referenced by get_relval_max_version().

524  """Returns tuple (CMSSW version, run version) for specified file."""
525  cmssw_version = re.findall('DQM_V(\d*)_', file)
526  run_version = re.findall('CMSSW_\d*_\d*_\d*(?:_[\w\d]*)?-[\w\d]*_V\d*\w?(?:_[\w\d]*)?-v(\d*)__', file)
527  if cmssw_version and run_version:
528  return (int(cmssw_version[0]), int(run_version[0]))
529 
def get_relval_version(file)
-------------—— Make files pairs: RelVal utils ---------------——
Definition: utils.py:523
def utils.get_relvaldata_cmssw_version (   file)
Returns tuple (CMSSW release, GR_R version) for specified RelValData file.

Definition at line 492 of file utils.py.

493  """Returns tuple (CMSSW release, GR_R version) for specified RelValData file."""
494  cmssw_release = re.findall('(CMSSW_\d*_\d*_\d*(?:_[\w\d]*)?)-', file)
495  gr_r_version = re.findall('-(GR_R_\d*_V\d*\w?)(?:_RelVal)?_', file)
496  if not gr_r_version:
497  gr_r_version = re.findall('CMSSW_\d*_\d*_\d*(?:_[\w\d]*)?-(\w*)_RelVal_', file)
498  if cmssw_release and gr_r_version:
499  return (cmssw_release[0], gr_r_version[0])
500 
def get_relvaldata_cmssw_version(file)
Definition: utils.py:492
def utils.get_relvaldata_id (   file)

-----------—— Make files pairs: RelValData utils --------------——

Returns unique relvaldata ID for a given file.

Definition at line 482 of file utils.py.

483  """Returns unique relvaldata ID for a given file."""
484  run_id = re.search('R\d{9}', file)
485  run = re.search('_RelVal_([\w\d]*)-v\d__', file)
486  if not run:
487  run = re.search('GR_R_\d*_V\d*C?_([\w\d]*)-v\d__', file)
488  if run_id and run:
489  return (run_id.group(), run.group(1))
490  return None
491 
def get_relvaldata_id(file)
-----------—— Make files pairs: RelValData utils --------------——
Definition: utils.py:482
def utils.get_relvaldata_max_version (   files)
Returns file with maximum version at a) beggining of the file,
e.g. DQM_V000M b) at the end of run, e.g. _run2012-vM. M has to be max.

Definition at line 510 of file utils.py.

References get_relvaldata_version().

511  """Returns file with maximum version at a) beggining of the file,
512  e.g. DQM_V000M b) at the end of run, e.g. _run2012-vM. M has to be max."""
513  max_file = files[0]
514  max_v = get_relvaldata_version(files[0])
515  for file in files:
516  file_v = get_relvaldata_version(file)
517  if file_v[1] > max_v[1] or ((file_v[1] == max_v[1]) and (file_v[0] > max_v[0])):
518  max_file = file
519  max_v = file_v
520  return max_file
521 
def get_relvaldata_version(file)
Definition: utils.py:501
def get_relvaldata_max_version(files)
Definition: utils.py:510
def utils.get_relvaldata_version (   file)
Returns tuple (CMSSW version, run version) for specified file.

Definition at line 501 of file utils.py.

References createfilelist.int.

Referenced by get_relvaldata_max_version().

502  """Returns tuple (CMSSW version, run version) for specified file."""
503  cmssw_version = re.findall('DQM_V(\d*)_', file)
504  run_version = re.findall('_RelVal_[\w\d]*-v(\d)__', file)
505  if not run_version:
506  run_version = re.findall('GR_R_\d*_V\d*C?_[\w\d]*-v(\d)__', file)
507  if cmssw_version and run_version:
508  return (int(cmssw_version[0]), int(run_version[0]))
509 
def get_relvaldata_version(file)
Definition: utils.py:501
def utils.getNbins (   h)
To be used in loops on bin number with range()
For each dimension there are GetNbinsX()+2 bins including underflow 
and overflow, and range() loops starts from 0. So the total number
of bins as upper limit of a range() loop already includes the next 
to last value needed.

Definition at line 92 of file utils.py.

Referenced by utils.Chi2.absval(), utils.BinToBin.do_test(), utils.BinToBin1percent.do_test(), and utils.StatisticalTest.get_rank().

92 def getNbins(h):
93  """
94  To be used in loops on bin number with range()
95  For each dimension there are GetNbinsX()+2 bins including underflow
96  and overflow, and range() loops starts from 0. So the total number
97  of bins as upper limit of a range() loop already includes the next
98  to last value needed.
99  """
100  biny=h.GetNbinsY()
101  if biny>1: biny+=2
102  binz=h.GetNbinsZ()
103  if binz>1:binz+=2
104  return (h.GetNbinsX()+2)*(biny)*(binz)
105 
106 #-------------------------------------------------------------------------------
107 
108 
def getNbins(h)
Definition: utils.py:92
def utils.is_empty (   h)

Definition at line 177 of file utils.py.

Referenced by DTSectColl.addTSTheta(), compileDMRTrends(), and utils.StatisticalTest.get_rank().

177 def is_empty(h):
178  for i in range(0,getNbins(h)):
179  if h.GetBinContent(i)!=0: return False
180  return True
181  #return h.GetSumOfWeights()==0
182 
183 #-------------------------------------------------------------------------------
184 
def getNbins(h)
Definition: utils.py:92
def is_empty(h)
Definition: utils.py:177
def utils.is_relvaldata (   files)

----------------------— Make files pairs -----------------------—

Definition at line 567 of file utils.py.

References any().

Referenced by make_files_pairs().

567 def is_relvaldata(files):
568  is_relvaldata_re = re.compile('_RelVal_')
569  return any([is_relvaldata_re.search(filename) for filename in files])
570 
bool any(const std::vector< T > &v, const T &what)
Definition: ECalSD.cc:37
def is_relvaldata(files)
----------------------— Make files pairs -----------------------—
Definition: utils.py:567
def utils.is_sparse (   h)

Definition at line 185 of file utils.py.

185 def is_sparse(h):
186  filled_bins=0.
187  nbins=h.GetNbinsX()
188  for ibin in range(0,nbins+2):
189  if h.GetBinContent(ibin)>0:
190  filled_bins+=1
191  #print "%s %s --> %s" %(filled_bins,nbins,filled_bins/nbins)
192  if filled_bins/nbins < .5:
193  return True
194  else:
195  return False
196 
197 #-------------------------------------------------------------------------------
198 
def is_sparse(h)
Definition: utils.py:185
def utils.literal2root (   literal,
  rootType 
)

Definition at line 69 of file utils.py.

References edm.print().

69 def literal2root (literal,rootType):
70  bitsarray = array.array('B')
71  bitsarray.fromstring(literal.decode('hex'))
72 
73  tbuffer=0
74  try:
75  tbuffer = TBufferFile(TBufferFile.kRead, len(bitsarray), bitsarray, False,0)
76  except:
77  print("could not transform to object array:")
78  print([ i for i in bitsarray ])
79 
80  # replace a couple of shortcuts with the real root class name
81  if rootType == 'TPROF':
82  rootType = 'TProfile'
83  if rootType == 'TPROF2D':
84  rootType = 'TProfile2D'
85 
86  root_class=eval(rootType+'.Class()')
87 
88  return tbuffer.ReadObject(root_class)
89 
90 #-------------------------------------------------------------------------------
91 
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def literal2root(literal, rootType)
Definition: utils.py:69
def utils.logger (   msg_level,
  message 
)

Definition at line 47 of file utils.py.

References edm.print().

47 def logger(msg_level,message):
48  if msg_level>=_log_level:
49  print("[%s] %s" %(asctime(),message))
50 
51 #-------------------------------------------------------------------------------
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def logger(msg_level, message)
Definition: utils.py:47
def utils.make_files_pairs (   files,
  verbose = True 
)

Definition at line 571 of file utils.py.

References mps_setup.append, cmsPerfStripChart.dict, cmsRelvalreport.exit, is_relvaldata(), SiStripPI.max, edm.print(), and str.

Referenced by ValidationMatrix.get_filenames_from_pool().

571 def make_files_pairs(files, verbose=True):
572  ## Select functions to use
573  if is_relvaldata(files):
574  is_relval_data = True
575  get_cmssw_version = get_relvaldata_cmssw_version
576  get_id = get_relvaldata_id
577  get_max_version = get_relvaldata_max_version
578  # print 'Pairing Data RelVal files.'
579  else:
580  is_relval_data = False
581  get_cmssw_version = get_relval_cmssw_version
582  get_id = get_relval_id
583  get_max_version = get_relval_max_version
584  # print 'Pairing Monte Carlo RelVal files.'
585 
586  ## Divide files into groups
587  versions_files = dict()
588  for file in files:
589  version = get_cmssw_version(file)
590  if version in versions_files:
591  versions_files[version].append(file)
592  else:
593  versions_files[version] = [file]
594 
595  ## Print the division into groups
596  if verbose:
597  print('\nFound versions:')
598  for version in versions_files:
599  print('%s: %d files' % (str(version), len(versions_files[version])))
600 
601  if len(versions_files) <= 1:
602  print('\nFound too little versions, there is nothing to pair. Exiting...\n')
603  exit()
604 
605  ## Select two biggest groups.
606  versions = versions_files.keys()
607  sizes = [len(value) for value in versions_files.values()]
608  v1 = versions[sizes.index(max(sizes))]
609  versions.remove(v1)
610  sizes.remove(max(sizes))
611  v2 = versions[sizes.index(max(sizes))]
612 
613  ## Print two biggest groups.
614  if verbose:
615  print('\nPairing %s (%d files) and %s (%d files)' % (str(v1),
616  len(versions_files[v1]), str(v2), len(versions_files[v2])))
617 
618  ## Pairing two versions
619  print('\nGot pairs:')
620  pairs = []
621  for unique_id in set([get_id(file) for file in versions_files[v1]]):
622  if is_relval_data:
623  dataset_re = re.compile(unique_id[0]+'_')
624  run_re = re.compile(unique_id[1])
625  c1_files = [file for file in versions_files[v1] if dataset_re.search(file) and run_re.search(file)]
626  c2_files = [file for file in versions_files[v2] if dataset_re.search(file) and run_re.search(file)]
627  else:
628  dataset_re = re.compile(unique_id[0]+'_')
629  ps_re = re.compile(unique_id[1])
630  ##compile a PU re and search also for same PU
631  c1_files = [file for file in versions_files[v1] if dataset_re.search(file) and ps_re.search(file)]
632  c2_files = [file for file in versions_files[v2] if dataset_re.search(file) and ps_re.search(file)]
633 
634  if len(c1_files) > 0 and len(c2_files) > 0:
635  first_file = get_max_version(c1_files)
636  second_file = get_max_version(c2_files)
637  print('%s\n%s\n' % (first_file, second_file))
638  pairs.extend((first_file, second_file))
639  if verbose:
640  print("Paired and got %d files.\n" % len(pairs))
641  return pairs
642 
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def is_relvaldata(files)
----------------------— Make files pairs -----------------------—
Definition: utils.py:567
def make_files_pairs(files, verbose=True)
Definition: utils.py:571
#define str(s)
def utils.parse_word (   word)

Definition at line 23 of file utils.py.

Referenced by pkg.AbstractPkg.tmpl_tags().

23 def parse_word(word):
24  "Parse word which contas double underscore tag"
25  output = set()
26  words = word.split()
27  for idx in range(0, len(words)):
28  pat = words[idx]
29  if pat and len(pat) > 4 and pat[:2] == '__': # we found enclosure
30  tag = pat[2:pat.rfind('__')]
31  if tag.find('__') != -1: # another pattern
32  for item in tag.split('__'):
33  if TAG.match(item):
34  output.add('__%s__' % item)
35  else:
36  output.add('__%s__' % tag)
37  return output
38 
def parse_word(word)
Definition: utils.py:23
def utils.profile2histo (   profile)

Definition at line 226 of file utils.py.

226 def profile2histo(profile):
227  if not profile.InheritsFrom("TH1"):
228  return profile
229 
230  bin_low_edges=[]
231  n_bins=profile.GetNbinsX()
232 
233  for ibin in range(1,n_bins+2):
234  bin_low_edges.append(profile.GetBinLowEdge(ibin))
235  bin_low_edges=array.array('f',bin_low_edges)
236  histo=TH1F(profile.GetName(),profile.GetTitle(),n_bins,bin_low_edges)
237  for ibin in range(0,n_bins+2):
238  histo.SetBinContent(ibin,profile.GetBinContent(ibin))
239  histo.SetBinError(ibin,profile.GetBinError(ibin))
240 
241  return histo
242 #-------------------------------------------------------------------------------
243 
def profile2histo(profile)
Definition: utils.py:226
def utils.setTDRStyle ( )

Definition at line 52 of file utils.py.

References compare_using_db.dirname.

52 def setTDRStyle():
53  this_dir=dirname(this_module_name)
54  this_dir_one_up=this_dir[:this_dir.rfind("/")+1]
55  #this_dir_two_up=this_dir_one_up[:this_dir_one_up.rfind("/")+1]
56  style_file=''
57  if "RELMON_SA" in os.environ:
58  style_file=this_dir_one_up+"data/tdrstyle_mod.C"
59  else:
60  style_file="%s/src/Utilities/RelMon/data/tdrstyle_mod.C"%(os.environ["CMSSW_BASE"])
61  try:
62  gROOT.ProcessLine(".L %s" %style_file)
63  gROOT.ProcessLine("setTDRStyle()")
64  except:
65  "Print could not set the TDR style. File %s not found?" %style_file
66 
67 
68 #-------------------------------------------------------------------------------
def setTDRStyle()
Definition: utils.py:52
def utils.test_env (   tdir,
  tmpl 
)
Test user environment, look-up if user has run cmsenv, otherwise
provide meaningful error message back to the user.

Definition at line 39 of file utils.py.

References edm.print().

Referenced by main.generator().

39 def test_env(tdir, tmpl):
40  """
41  Test user environment, look-up if user has run cmsenv, otherwise
42  provide meaningful error message back to the user.
43  """
44  if not tdir or not os.path.isdir(tdir):
45  print("Unable to access template dir: %s" % tdir)
46  sys.exit(1)
47  if not os.listdir(tdir):
48  print("No template files found in template dir %s" % tdir)
49  sys.exit(0)
50  if not tmpl:
51  msg = "No template type is provided, "
52  msg += "see available templates via --templates option"
53  print(msg)
54  sys.exit(1)
55 
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def test_env(tdir, tmpl)
Definition: utils.py:39
def utils.to_datetime (   date_string)
Takes a date string with the format Y-m-d H:m:S.f and gives back a datetime.datetime object

Definition at line 12 of file utils.py.

Referenced by querying_tests.global_tag_tests().

12 def to_datetime(date_string):
13  """
14  Takes a date string with the format Y-m-d H:m:S.f and gives back a datetime.datetime object
15  """
16  return datetime.datetime.strptime(date_string.replace(",", "."), "%Y-%m-%d %H:%M:%S.%f")
17 
def to_datetime(date_string)
Definition: utils.py:12
def utils.to_timestamp (   obj)
Takes a datetime object and outputs a timestamp string with the format Y-m-d H:m:S.f

Definition at line 6 of file utils.py.

Referenced by uploads.uploader.filter_iovs_by_fcsr(), models.generate(), uploads.log(), and uploads.uploader.send_blob().

6 def to_timestamp(obj):
7  """
8  Takes a datetime object and outputs a timestamp string with the format Y-m-d H:m:S.f
9  """
10  return obj.strftime('%Y-%m-%d %H:%M:%S.%f') if isinstance(obj, datetime.datetime) else obj
11 
def to_timestamp(obj)
Definition: utils.py:6
def utils.tree (   idir)

Definition at line 129 of file utils.py.

References edm.print().

129 def tree(idir):
130  "Print directory content, similar to tree UNIX command"
131  if idir[-1] == '/':
132  idir = idir[-1]
133  dsep = ''
134  fsep = ''
135  dtot = -1 # we'll not count initial directory
136  ftot = 0
137  for root, dirs, files in os.walk(idir):
138  dirs = root.split('/')
139  ndirs = len(dirs)
140  if ndirs > 1:
141  dsep = '| '*(ndirs-1)
142  print('%s%s/' % (dsep, dirs[-1]))
143  dtot += 1
144  for fname in files:
145  fsep = dsep + '|--'
146  print('%s %s' % (fsep, fname))
147  ftot += 1
148  if dtot == -1 or not dtot:
149  dmsg = ''
150  else:
151  dmsg = '%s directories,' % dtot
152  if ftot:
153  fmsg = '%s file' % ftot
154  if ftot > 1:
155  fmsg += 's'
156  else:
157  fmsg = ''
158  if dmsg and fmsg:
159  print("Total: %s %s" % (dmsg, fmsg))
160  else:
161  print("No directories/files in %s" % idir)
162 
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def tree(idir)
Definition: utils.py:129
def utils.user_info (   ainput = None)

Definition at line 98 of file utils.py.

98 def user_info(ainput=None):
99  "Return user name and office location, based on UNIX finger"
100  if ainput:
101  return ainput
102  pwdstr = pwd.getpwnam(os.getlogin())
103  author = pwdstr.pw_gecos
104  if author and isinstance(author, str):
105  author = author.split(',')[0]
106  return author
107 
def user_info(ainput=None)
Definition: utils.py:98
def utils.wget (   url)
Fetch the WHOLE file, not in bunches... To be optimised.

Definition at line 457 of file utils.py.

References estimatePileup.basename, and edm.print().

457 def wget(url):
458  """ Fetch the WHOLE file, not in bunches... To be optimised.
459  """
460  opener=build_opener(X509CertOpen())
461  datareq = Request(url)
462  datareq.add_header('authenticated_wget', "The ultimate wgetter")
463  bin_content=None
464  try:
465  filename=basename(url)
466  print("Checking existence of file %s on disk..."%filename)
467  if not isfile("./%s"%filename):
468  bin_content=opener.open(datareq).read()
469  else:
470  print("File %s exists, skipping.." %filename)
471  except ValueError:
472  print("Error: Unknown url %s" %url)
473 
474  if bin_content!=None:
475  ofile = open(filename, 'wb')
476  ofile.write(bin_content)
477  ofile.close()
478 
479 #-------------------------------------------------------------------------------
def wget(url)
Definition: utils.py:457
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66

Variable Documentation

utils._log_level
private

Definition at line 46 of file utils.py.

utils.argv

Definition at line 25 of file utils.py.

utils.gErrorIgnoreLevel

Definition at line 28 of file utils.py.

Referenced by main(), FWFileEntry.openFile(), PlotDMRTrends(), TkAlStyle.set(), and topLevelPSet().

utils.theargv

Definition at line 24 of file utils.py.