CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
utils.py
Go to the documentation of this file.
1 #-*- coding: utf-8 -*-
2 #pylint: disable-msg=W0122,R0914
3 
4 """
5 File : utils.py
6 Author : Valentin Kuznetsov <vkuznet@gmail.com>
7 Description: Utilities module
8 """
9 
10 # system modules
11 import os
12 import re
13 import sys
14 import pwd
15 import pprint
16 import subprocess
17 
18 # template tag pattern
19 TAG = re.compile(r'[a-zA-Z0-9]')
20 
21 def parse_word(word):
22  "Parse word which contas double underscore tag"
23  output = set()
24  words = word.split()
25  for idx in xrange(0, len(words)):
26  pat = words[idx]
27  if pat and len(pat) > 4 and pat[:2] == '__': # we found enclosure
28  tag = pat[2:pat.rfind('__')]
29  if tag.find('__') != -1: # another pattern
30  for item in tag.split('__'):
31  if TAG.match(item):
32  output.add('__%s__' % item)
33  else:
34  output.add('__%s__' % tag)
35  return output
36 
37 def test_env(tdir, tmpl):
38  """
39  Test user environment, look-up if user has run cmsenv, otherwise
40  provide meaningful error message back to the user.
41  """
42  if not tdir or not os.path.isdir(tdir):
43  print "Unable to access template dir: %s" % tdir
44  sys.exit(1)
45  if not os.listdir(tdir):
46  print "No template files found in template dir %s" % tdir
47  sys.exit(0)
48  if not tmpl:
49  msg = "No template type is provided, "
50  msg += "see available templates via --templates option"
51  print msg
52  sys.exit(1)
53 
54 def functor(code, kwds, debug=0):
55  """
56  Auto-generate and execute function with given code and configuration
57  For details of compile/exec/eval see
58  http://lucumr.pocoo.org/2011/2/1/exec-in-python/
59  """
60  args = []
61  for key, val in kwds.items():
62  if isinstance(val, basestring):
63  arg = '%s="%s"' % (key, val)
64  elif isinstance(val, list):
65  arg = '%s=%s' % (key, val)
66  else:
67  msg = 'Unsupported data type "%s" <%s>' % (val, type(val))
68  raise Exception(msg)
69  args.append(arg)
70  func = '\nimport sys'
71  func += '\nimport StringIO'
72  func += "\ndef func(%s):\n" % ','.join(args)
73  func += code
74  func += """
75 def capture():
76  "Capture snippet printous"
77  old_stdout = sys.stdout
78  sys.stdout = StringIO.StringIO()
79  func()
80  out = sys.stdout.getvalue()
81  sys.stdout = old_stdout
82  return out\n
83 capture()\n"""
84  if debug:
85  print "\n### generated code\n"
86  print func
87  # compile python code as exec statement
88  obj = compile(func, '<string>', 'exec')
89  # define execution namespace
90  namespace = {}
91  # execute compiled python code in given namespace
92  exec obj in namespace
93  # located generated function object, run it and return its results
94  return namespace['capture']()
95 
96 def user_info(ainput=None):
97  "Return user name and office location, based on UNIX finger"
98  if ainput:
99  return ainput
100  pwdstr = pwd.getpwnam(os.getlogin())
101  author = pwdstr.pw_gecos
102  if author and isinstance(author, basestring):
103  author = author.split(',')[0]
104  return author
105 
106 def code_generator(kwds):
107  """
108  Code generator function, parse user arguments, load and
109  return appropriate template generator module.
110  """
111  debug = kwds.get('debug', None)
112  if debug:
113  print "Configuration:"
114  pprint.pprint(kwds)
115  try:
116  klass = kwds.get('tmpl')
117  mname = 'FWCore.Skeletons.%s' % klass.lower()
118  module = __import__(mname, fromlist=[klass])
119  except ImportError as err:
120  klass = 'AbstractPkg'
121  module = __import__('FWCore.Skeletons.pkg', fromlist=[klass])
122  if debug:
123  print "%s, will use %s" % (str(err), klass)
124  obj = getattr(module, klass)(kwds)
125  return obj
126 
127 def tree(idir):
128  "Print directory content, similar to tree UNIX command"
129  if idir[-1] == '/':
130  idir = idir[-1]
131  dsep = ''
132  fsep = ''
133  dtot = -1 # we'll not count initial directory
134  ftot = 0
135  for root, dirs, files in os.walk(idir):
136  dirs = root.split('/')
137  ndirs = len(dirs)
138  if ndirs > 1:
139  dsep = '| '*(ndirs-1)
140  print '%s%s/' % (dsep, dirs[-1])
141  dtot += 1
142  for fname in files:
143  fsep = dsep + '|--'
144  print '%s %s' % (fsep, fname)
145  ftot += 1
146  if dtot == -1 or not dtot:
147  dmsg = ''
148  else:
149  dmsg = '%s directories,' % dtot
150  if ftot:
151  fmsg = '%s file' % ftot
152  if ftot > 1:
153  fmsg += 's'
154  else:
155  fmsg = ''
156  if dmsg and fmsg:
157  print "Total: %s %s" % (dmsg, fmsg)
158  else:
159  print "No directories/files in %s" % idir
def tree
Definition: utils.py:127
def parse_word
Definition: utils.py:21
def functor
Definition: utils.py:54
def user_info
Definition: utils.py:96
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def code_generator
Definition: utils.py:106
def test_env
Definition: utils.py:37