CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
helperFunctions.py
Go to the documentation of this file.
1 import os
2 import ROOT
3 from TkAlExceptions import AllInOneError
4 
5 ####################--- Helpers ---############################
6 def replaceByMap(target, the_map):
7  """This function replaces `.oO[key]Oo.` by `the_map[key]` in target.
8 
9  Arguments:
10  - `target`: String which contains symbolic tags of the form `.oO[key]Oo.`
11  - `the_map`: Dictionary which has to contain the `key`s in `target` as keys
12  """
13 
14  result = target
15  for key in the_map:
16  lifeSaver = 10e3
17  iteration = 0
18  while ".oO[" in result and "]Oo." in result:
19  for key in the_map:
20  try:
21  result = result.replace(".oO["+key+"]Oo.",the_map[key])
22  except TypeError: #try a dict
23  try:
24  for keykey, value in the_map[key].iteritems():
25  result = result.replace(".oO[" + key + "['" + keykey + "']]Oo.", value)
26  result = result.replace(".oO[" + key + '["' + keykey + '"]]Oo.', value)
27  except AttributeError: #try a list
28  try:
29  for index, value in enumerate(the_map[key]):
30  result = result.replace(".oO[" + key + "[" + str(index) + "]]Oo.", value)
31  except TypeError:
32  raise TypeError("Something is wrong in replaceByMap! Need a string, dict, or list, but the_map(%s)=%s!"%(repr(key), repr(the_map[key])))
33  iteration += 1
34  if iteration > lifeSaver:
35  problematicLines = ""
36  for line in result.splitlines():
37  if ".oO[" in result and "]Oo." in line:
38  problematicLines += "%s\n"%line
39  msg = ("Oh Dear, there seems to be an endless loop in "
40  "replaceByMap!!\n%s\n%s"%(problematicLines, the_map))
41  raise AllInOneError(msg)
42  return result
43 
44 
45 def getCommandOutput2(command):
46  """This function executes `command` and returns it output.
47 
48  Arguments:
49  - `command`: Shell command to be invoked by this function.
50  """
51 
52  child = os.popen(command)
53  data = child.read()
54  err = child.close()
55  if err:
56  raise RuntimeError('%s failed w/ exit code %d' % (command, err))
57  return data
58 
59 
60 def castorDirExists(path):
61  """This function checks if the directory given by `path` exists.
62 
63  Arguments:
64  - `path`: Path to castor directory
65  """
66 
67  if path[-1] == "/":
68  path = path[:-1]
69  containingPath = os.path.join( *path.split("/")[:-1] )
70  dirInQuestion = path.split("/")[-1]
71  try:
72  rawLines = getCommandOutput2("rfdir /"+containingPath).splitlines()
73  except RuntimeError:
74  return False
75  for line in rawLines:
76  if line.split()[0][0] == "d":
77  if line.split()[8] == dirInQuestion:
78  return True
79  return False
80 
81 def replacelast(string, old, new, count = 1):
82  """Replace the last occurances of a string"""
83  return new.join(string.rsplit(old,count))
84 
85 fileExtensions = ["_cfg.py", ".sh", ".root"]
86 
87 def addIndex(filename, njobs, index = None):
88  if index is None:
89  return [addIndex(filename, njobs, i) for i in range(njobs)]
90  if njobs == 1:
91  return filename
92 
93  fileExtension = None
94  for extension in fileExtensions:
95  if filename.endswith(extension):
96  fileExtension = extension
97  if fileExtension is None:
98  raise AllInOneError(fileName + " does not end with any of the extensions "
99  + str(fileExtensions))
100  return replacelast(filename, fileExtension, "_" + str(index) + fileExtension)
101 
102 def parsecolor(color):
103  try: #simplest case: it's an int
104  return int(color)
105  except ValueError:
106  pass
107 
108  try: #kRed, kBlue, ...
109  color = str(getattr(ROOT, color))
110  return int(color)
111  except (AttributeError, ValueError):
112  pass
113 
114  if color.count("+") + color.count("-") == 1: #kRed+5, kGreen-2
115  if "+" in color: #don't want to deal with nonassociativity of -
116  split = color.split("+")
117  color1 = parsecolor(split[0])
118  color2 = parsecolor(split[1])
119  return color1 + color2
120 
121  if "-" in color:
122  split = color.split("-")
123  color1 = parsecolor(split[0])
124  color2 = parsecolor(split[1])
125  return color1 - color2
126 
127  raise AllInOneError("color has to be an integer, a ROOT constant (kRed, kBlue, ...), or a two-term sum or difference (kGreen-5)!")
128 
129 def parsestyle(style):
130  try:
131  int(style)
132  return style
133  except ValueError:
134  raise AllInOneError("style has to be an integer!")
def replaceByMap
— Helpers —############################