You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1629 lines
52 KiB

6 years ago
  1. """SCons.Util
  2. Various utility functions go here.
  3. """
  4. #
  5. # Copyright (c) 2001 - 2017 The SCons Foundation
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining
  8. # a copy of this software and associated documentation files (the
  9. # "Software"), to deal in the Software without restriction, including
  10. # without limitation the rights to use, copy, modify, merge, publish,
  11. # distribute, sublicense, and/or sell copies of the Software, and to
  12. # permit persons to whom the Software is furnished to do so, subject to
  13. # the following conditions:
  14. #
  15. # The above copyright notice and this permission notice shall be included
  16. # in all copies or substantial portions of the Software.
  17. #
  18. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  19. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  20. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  21. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  22. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  23. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  24. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  25. __revision__ = "src/engine/SCons/Util.py rel_3.0.0:4395:8972f6a2f699 2017/09/18 12:59:24 bdbaddog"
  26. import os
  27. import sys
  28. import copy
  29. import re
  30. import types
  31. import codecs
  32. import pprint
  33. PY3 = sys.version_info[0] == 3
  34. try:
  35. from UserDict import UserDict
  36. except ImportError as e:
  37. from collections import UserDict
  38. try:
  39. from UserList import UserList
  40. except ImportError as e:
  41. from collections import UserList
  42. from collections import Iterable
  43. try:
  44. from UserString import UserString
  45. except ImportError as e:
  46. from collections import UserString
  47. # Don't "from types import ..." these because we need to get at the
  48. # types module later to look for UnicodeType.
  49. # Below not used?
  50. # InstanceType = types.InstanceType
  51. MethodType = types.MethodType
  52. FunctionType = types.FunctionType
  53. try:
  54. unicode
  55. except NameError:
  56. UnicodeType = str
  57. else:
  58. UnicodeType = unicode
  59. def dictify(keys, values, result={}):
  60. for k, v in zip(keys, values):
  61. result[k] = v
  62. return result
  63. _altsep = os.altsep
  64. if _altsep is None and sys.platform == 'win32':
  65. # My ActivePython 2.0.1 doesn't set os.altsep! What gives?
  66. _altsep = '/'
  67. if _altsep:
  68. def rightmost_separator(path, sep):
  69. return max(path.rfind(sep), path.rfind(_altsep))
  70. else:
  71. def rightmost_separator(path, sep):
  72. return path.rfind(sep)
  73. # First two from the Python Cookbook, just for completeness.
  74. # (Yeah, yeah, YAGNI...)
  75. def containsAny(str, set):
  76. """Check whether sequence str contains ANY of the items in set."""
  77. for c in set:
  78. if c in str: return 1
  79. return 0
  80. def containsAll(str, set):
  81. """Check whether sequence str contains ALL of the items in set."""
  82. for c in set:
  83. if c not in str: return 0
  84. return 1
  85. def containsOnly(str, set):
  86. """Check whether sequence str contains ONLY items in set."""
  87. for c in str:
  88. if c not in set: return 0
  89. return 1
  90. def splitext(path):
  91. "Same as os.path.splitext() but faster."
  92. sep = rightmost_separator(path, os.sep)
  93. dot = path.rfind('.')
  94. # An ext is only real if it has at least one non-digit char
  95. if dot > sep and not containsOnly(path[dot:], "0123456789."):
  96. return path[:dot],path[dot:]
  97. else:
  98. return path,""
  99. def updrive(path):
  100. """
  101. Make the drive letter (if any) upper case.
  102. This is useful because Windows is inconsistent on the case
  103. of the drive letter, which can cause inconsistencies when
  104. calculating command signatures.
  105. """
  106. drive, rest = os.path.splitdrive(path)
  107. if drive:
  108. path = drive.upper() + rest
  109. return path
  110. class NodeList(UserList):
  111. """This class is almost exactly like a regular list of Nodes
  112. (actually it can hold any object), with one important difference.
  113. If you try to get an attribute from this list, it will return that
  114. attribute from every item in the list. For example:
  115. >>> someList = NodeList([ ' foo ', ' bar ' ])
  116. >>> someList.strip()
  117. [ 'foo', 'bar' ]
  118. """
  119. # def __init__(self, initlist=None):
  120. # self.data = []
  121. # # print("TYPE:%s"%type(initlist))
  122. # if initlist is not None:
  123. # # XXX should this accept an arbitrary sequence?
  124. # if type(initlist) == type(self.data):
  125. # self.data[:] = initlist
  126. # elif isinstance(initlist, (UserList, NodeList)):
  127. # self.data[:] = initlist.data[:]
  128. # elif isinstance(initlist, Iterable):
  129. # self.data = list(initlist)
  130. # else:
  131. # self.data = [ initlist,]
  132. def __nonzero__(self):
  133. return len(self.data) != 0
  134. def __bool__(self):
  135. return self.__nonzero__()
  136. def __str__(self):
  137. return ' '.join(map(str, self.data))
  138. def __iter__(self):
  139. return iter(self.data)
  140. def __call__(self, *args, **kwargs):
  141. result = [x(*args, **kwargs) for x in self.data]
  142. return self.__class__(result)
  143. def __getattr__(self, name):
  144. result = [getattr(x, name) for x in self.data]
  145. return self.__class__(result)
  146. def __getitem__(self, index):
  147. """
  148. This comes for free on py2,
  149. but py3 slices of NodeList are returning a list
  150. breaking slicing nodelist and refering to
  151. properties and methods on contained object
  152. """
  153. # return self.__class__(self.data[index])
  154. if isinstance(index, slice):
  155. # Expand the slice object using range()
  156. # limited by number of items in self.data
  157. indices = index.indices(len(self.data))
  158. return self.__class__([self[x] for x in
  159. range(*indices)])
  160. else:
  161. # Return one item of the tart
  162. return self.data[index]
  163. _get_env_var = re.compile(r'^\$([_a-zA-Z]\w*|{[_a-zA-Z]\w*})$')
  164. def get_environment_var(varstr):
  165. """Given a string, first determine if it looks like a reference
  166. to a single environment variable, like "$FOO" or "${FOO}".
  167. If so, return that variable with no decorations ("FOO").
  168. If not, return None."""
  169. mo=_get_env_var.match(to_String(varstr))
  170. if mo:
  171. var = mo.group(1)
  172. if var[0] == '{':
  173. return var[1:-1]
  174. else:
  175. return var
  176. else:
  177. return None
  178. class DisplayEngine(object):
  179. print_it = True
  180. def __call__(self, text, append_newline=1):
  181. if not self.print_it:
  182. return
  183. if append_newline: text = text + '\n'
  184. try:
  185. sys.stdout.write(UnicodeType(text))
  186. except IOError:
  187. # Stdout might be connected to a pipe that has been closed
  188. # by now. The most likely reason for the pipe being closed
  189. # is that the user has press ctrl-c. It this is the case,
  190. # then SCons is currently shutdown. We therefore ignore
  191. # IOError's here so that SCons can continue and shutdown
  192. # properly so that the .sconsign is correctly written
  193. # before SCons exits.
  194. pass
  195. def set_mode(self, mode):
  196. self.print_it = mode
  197. def render_tree(root, child_func, prune=0, margin=[0], visited=None):
  198. """
  199. Render a tree of nodes into an ASCII tree view.
  200. :Parameters:
  201. - `root`: the root node of the tree
  202. - `child_func`: the function called to get the children of a node
  203. - `prune`: don't visit the same node twice
  204. - `margin`: the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe.
  205. - `visited`: a dictionary of visited nodes in the current branch if not prune, or in the whole tree if prune.
  206. """
  207. rname = str(root)
  208. # Initialize 'visited' dict, if required
  209. if visited is None:
  210. visited = {}
  211. children = child_func(root)
  212. retval = ""
  213. for pipe in margin[:-1]:
  214. if pipe:
  215. retval = retval + "| "
  216. else:
  217. retval = retval + " "
  218. if rname in visited:
  219. return retval + "+-[" + rname + "]\n"
  220. retval = retval + "+-" + rname + "\n"
  221. if not prune:
  222. visited = copy.copy(visited)
  223. visited[rname] = 1
  224. for i in range(len(children)):
  225. margin.append(i < len(children)-1)
  226. retval = retval + render_tree(children[i], child_func, prune, margin, visited)
  227. margin.pop()
  228. return retval
  229. IDX = lambda N: N and 1 or 0
  230. def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited=None):
  231. """
  232. Print a tree of nodes. This is like render_tree, except it prints
  233. lines directly instead of creating a string representation in memory,
  234. so that huge trees can be printed.
  235. :Parameters:
  236. - `root` - the root node of the tree
  237. - `child_func` - the function called to get the children of a node
  238. - `prune` - don't visit the same node twice
  239. - `showtags` - print status information to the left of each node line
  240. - `margin` - the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe.
  241. - `visited` - a dictionary of visited nodes in the current branch if not prune, or in the whole tree if prune.
  242. """
  243. rname = str(root)
  244. # Initialize 'visited' dict, if required
  245. if visited is None:
  246. visited = {}
  247. if showtags:
  248. if showtags == 2:
  249. legend = (' E = exists\n' +
  250. ' R = exists in repository only\n' +
  251. ' b = implicit builder\n' +
  252. ' B = explicit builder\n' +
  253. ' S = side effect\n' +
  254. ' P = precious\n' +
  255. ' A = always build\n' +
  256. ' C = current\n' +
  257. ' N = no clean\n' +
  258. ' H = no cache\n' +
  259. '\n')
  260. sys.stdout.write(legend)
  261. tags = ['[']
  262. tags.append(' E'[IDX(root.exists())])
  263. tags.append(' R'[IDX(root.rexists() and not root.exists())])
  264. tags.append(' BbB'[[0,1][IDX(root.has_explicit_builder())] +
  265. [0,2][IDX(root.has_builder())]])
  266. tags.append(' S'[IDX(root.side_effect)])
  267. tags.append(' P'[IDX(root.precious)])
  268. tags.append(' A'[IDX(root.always_build)])
  269. tags.append(' C'[IDX(root.is_up_to_date())])
  270. tags.append(' N'[IDX(root.noclean)])
  271. tags.append(' H'[IDX(root.nocache)])
  272. tags.append(']')
  273. else:
  274. tags = []
  275. def MMM(m):
  276. return [" ","| "][m]
  277. margins = list(map(MMM, margin[:-1]))
  278. children = child_func(root)
  279. if prune and rname in visited and children:
  280. sys.stdout.write(''.join(tags + margins + ['+-[', rname, ']']) + '\n')
  281. return
  282. sys.stdout.write(''.join(tags + margins + ['+-', rname]) + '\n')
  283. visited[rname] = 1
  284. if children:
  285. margin.append(1)
  286. idx = IDX(showtags)
  287. for C in children[:-1]:
  288. print_tree(C, child_func, prune, idx, margin, visited)
  289. margin[-1] = 0
  290. print_tree(children[-1], child_func, prune, idx, margin, visited)
  291. margin.pop()
  292. # Functions for deciding if things are like various types, mainly to
  293. # handle UserDict, UserList and UserString like their underlying types.
  294. #
  295. # Yes, all of this manual testing breaks polymorphism, and the real
  296. # Pythonic way to do all of this would be to just try it and handle the
  297. # exception, but handling the exception when it's not the right type is
  298. # often too slow.
  299. # We are using the following trick to speed up these
  300. # functions. Default arguments are used to take a snapshot of
  301. # the global functions and constants used by these functions. This
  302. # transforms accesses to global variable into local variables
  303. # accesses (i.e. LOAD_FAST instead of LOAD_GLOBAL).
  304. DictTypes = (dict, UserDict)
  305. ListTypes = (list, UserList)
  306. SequenceTypes = (list, tuple, UserList)
  307. # Note that profiling data shows a speed-up when comparing
  308. # explicitly with str and unicode instead of simply comparing
  309. # with basestring. (at least on Python 2.5.1)
  310. try:
  311. StringTypes = (str, unicode, UserString)
  312. except NameError:
  313. StringTypes = (str, UserString)
  314. # Empirically, it is faster to check explicitly for str and
  315. # unicode than for basestring.
  316. try:
  317. BaseStringTypes = (str, unicode)
  318. except NameError:
  319. BaseStringTypes = (str)
  320. def is_Dict(obj, isinstance=isinstance, DictTypes=DictTypes):
  321. return isinstance(obj, DictTypes)
  322. def is_List(obj, isinstance=isinstance, ListTypes=ListTypes):
  323. return isinstance(obj, ListTypes)
  324. def is_Sequence(obj, isinstance=isinstance, SequenceTypes=SequenceTypes):
  325. return isinstance(obj, SequenceTypes)
  326. def is_Tuple(obj, isinstance=isinstance, tuple=tuple):
  327. return isinstance(obj, tuple)
  328. def is_String(obj, isinstance=isinstance, StringTypes=StringTypes):
  329. return isinstance(obj, StringTypes)
  330. def is_Scalar(obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes):
  331. # Profiling shows that there is an impressive speed-up of 2x
  332. # when explicitly checking for strings instead of just not
  333. # sequence when the argument (i.e. obj) is already a string.
  334. # But, if obj is a not string then it is twice as fast to
  335. # check only for 'not sequence'. The following code therefore
  336. # assumes that the obj argument is a string most of the time.
  337. return isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes)
  338. def do_flatten(sequence, result, isinstance=isinstance,
  339. StringTypes=StringTypes, SequenceTypes=SequenceTypes):
  340. for item in sequence:
  341. if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes):
  342. result.append(item)
  343. else:
  344. do_flatten(item, result)
  345. def flatten(obj, isinstance=isinstance, StringTypes=StringTypes,
  346. SequenceTypes=SequenceTypes, do_flatten=do_flatten):
  347. """Flatten a sequence to a non-nested list.
  348. Flatten() converts either a single scalar or a nested sequence
  349. to a non-nested list. Note that flatten() considers strings
  350. to be scalars instead of sequences like Python would.
  351. """
  352. if isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes):
  353. return [obj]
  354. result = []
  355. for item in obj:
  356. if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes):
  357. result.append(item)
  358. else:
  359. do_flatten(item, result)
  360. return result
  361. def flatten_sequence(sequence, isinstance=isinstance, StringTypes=StringTypes,
  362. SequenceTypes=SequenceTypes, do_flatten=do_flatten):
  363. """Flatten a sequence to a non-nested list.
  364. Same as flatten(), but it does not handle the single scalar
  365. case. This is slightly more efficient when one knows that
  366. the sequence to flatten can not be a scalar.
  367. """
  368. result = []
  369. for item in sequence:
  370. if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes):
  371. result.append(item)
  372. else:
  373. do_flatten(item, result)
  374. return result
  375. # Generic convert-to-string functions that abstract away whether or
  376. # not the Python we're executing has Unicode support. The wrapper
  377. # to_String_for_signature() will use a for_signature() method if the
  378. # specified object has one.
  379. #
  380. def to_String(s,
  381. isinstance=isinstance, str=str,
  382. UserString=UserString, BaseStringTypes=BaseStringTypes):
  383. if isinstance(s,BaseStringTypes):
  384. # Early out when already a string!
  385. return s
  386. elif isinstance(s, UserString):
  387. # s.data can only be either a unicode or a regular
  388. # string. Please see the UserString initializer.
  389. return s.data
  390. else:
  391. return str(s)
  392. def to_String_for_subst(s,
  393. isinstance=isinstance, str=str, to_String=to_String,
  394. BaseStringTypes=BaseStringTypes, SequenceTypes=SequenceTypes,
  395. UserString=UserString):
  396. # Note that the test cases are sorted by order of probability.
  397. if isinstance(s, BaseStringTypes):
  398. return s
  399. elif isinstance(s, SequenceTypes):
  400. l = []
  401. for e in s:
  402. l.append(to_String_for_subst(e))
  403. return ' '.join( s )
  404. elif isinstance(s, UserString):
  405. # s.data can only be either a unicode or a regular
  406. # string. Please see the UserString initializer.
  407. return s.data
  408. else:
  409. return str(s)
  410. def to_String_for_signature(obj, to_String_for_subst=to_String_for_subst,
  411. AttributeError=AttributeError):
  412. try:
  413. f = obj.for_signature
  414. except AttributeError:
  415. if isinstance(obj, dict):
  416. # pprint will output dictionary in key sorted order
  417. # with py3.5 the order was randomized. In general depending on dictionary order
  418. # which was undefined until py3.6 (where it's by insertion order) was not wise.
  419. return pprint.pformat(obj, width=1000000)
  420. else:
  421. return to_String_for_subst(obj)
  422. else:
  423. return f()
  424. # The SCons "semi-deep" copy.
  425. #
  426. # This makes separate copies of lists (including UserList objects)
  427. # dictionaries (including UserDict objects) and tuples, but just copies
  428. # references to anything else it finds.
  429. #
  430. # A special case is any object that has a __semi_deepcopy__() method,
  431. # which we invoke to create the copy. Currently only used by
  432. # BuilderDict to actually prevent the copy operation (as invalid on that object).
  433. #
  434. # The dispatch table approach used here is a direct rip-off from the
  435. # normal Python copy module.
  436. _semi_deepcopy_dispatch = d = {}
  437. def semi_deepcopy_dict(x, exclude = [] ):
  438. copy = {}
  439. for key, val in x.items():
  440. # The regular Python copy.deepcopy() also deepcopies the key,
  441. # as follows:
  442. #
  443. # copy[semi_deepcopy(key)] = semi_deepcopy(val)
  444. #
  445. # Doesn't seem like we need to, but we'll comment it just in case.
  446. if key not in exclude:
  447. copy[key] = semi_deepcopy(val)
  448. return copy
  449. d[dict] = semi_deepcopy_dict
  450. def _semi_deepcopy_list(x):
  451. return list(map(semi_deepcopy, x))
  452. d[list] = _semi_deepcopy_list
  453. def _semi_deepcopy_tuple(x):
  454. return tuple(map(semi_deepcopy, x))
  455. d[tuple] = _semi_deepcopy_tuple
  456. def semi_deepcopy(x):
  457. copier = _semi_deepcopy_dispatch.get(type(x))
  458. if copier:
  459. return copier(x)
  460. else:
  461. if hasattr(x, '__semi_deepcopy__') and callable(x.__semi_deepcopy__):
  462. return x.__semi_deepcopy__()
  463. elif isinstance(x, UserDict):
  464. return x.__class__(semi_deepcopy_dict(x))
  465. elif isinstance(x, UserList):
  466. return x.__class__(_semi_deepcopy_list(x))
  467. return x
  468. class Proxy(object):
  469. """A simple generic Proxy class, forwarding all calls to
  470. subject. So, for the benefit of the python newbie, what does
  471. this really mean? Well, it means that you can take an object, let's
  472. call it 'objA', and wrap it in this Proxy class, with a statement
  473. like this
  474. proxyObj = Proxy(objA),
  475. Then, if in the future, you do something like this
  476. x = proxyObj.var1,
  477. since Proxy does not have a 'var1' attribute (but presumably objA does),
  478. the request actually is equivalent to saying
  479. x = objA.var1
  480. Inherit from this class to create a Proxy.
  481. Note that, with new-style classes, this does *not* work transparently
  482. for Proxy subclasses that use special .__*__() method names, because
  483. those names are now bound to the class, not the individual instances.
  484. You now need to know in advance which .__*__() method names you want
  485. to pass on to the underlying Proxy object, and specifically delegate
  486. their calls like this:
  487. class Foo(Proxy):
  488. __str__ = Delegate('__str__')
  489. """
  490. def __init__(self, subject):
  491. """Wrap an object as a Proxy object"""
  492. self._subject = subject
  493. def __getattr__(self, name):
  494. """Retrieve an attribute from the wrapped object. If the named
  495. attribute doesn't exist, AttributeError is raised"""
  496. return getattr(self._subject, name)
  497. def get(self):
  498. """Retrieve the entire wrapped object"""
  499. return self._subject
  500. def __eq__(self, other):
  501. if issubclass(other.__class__, self._subject.__class__):
  502. return self._subject == other
  503. return self.__dict__ == other.__dict__
  504. class Delegate(object):
  505. """A Python Descriptor class that delegates attribute fetches
  506. to an underlying wrapped subject of a Proxy. Typical use:
  507. class Foo(Proxy):
  508. __str__ = Delegate('__str__')
  509. """
  510. def __init__(self, attribute):
  511. self.attribute = attribute
  512. def __get__(self, obj, cls):
  513. if isinstance(obj, cls):
  514. return getattr(obj._subject, self.attribute)
  515. else:
  516. return self
  517. # attempt to load the windows registry module:
  518. can_read_reg = 0
  519. try:
  520. import winreg
  521. can_read_reg = 1
  522. hkey_mod = winreg
  523. RegOpenKeyEx = winreg.OpenKeyEx
  524. RegEnumKey = winreg.EnumKey
  525. RegEnumValue = winreg.EnumValue
  526. RegQueryValueEx = winreg.QueryValueEx
  527. RegError = winreg.error
  528. except ImportError:
  529. try:
  530. import win32api
  531. import win32con
  532. can_read_reg = 1
  533. hkey_mod = win32con
  534. RegOpenKeyEx = win32api.RegOpenKeyEx
  535. RegEnumKey = win32api.RegEnumKey
  536. RegEnumValue = win32api.RegEnumValue
  537. RegQueryValueEx = win32api.RegQueryValueEx
  538. RegError = win32api.error
  539. except ImportError:
  540. class _NoError(Exception):
  541. pass
  542. RegError = _NoError
  543. WinError = None
  544. # Make sure we have a definition of WindowsError so we can
  545. # run platform-independent tests of Windows functionality on
  546. # platforms other than Windows. (WindowsError is, in fact, an
  547. # OSError subclass on Windows.)
  548. class PlainWindowsError(OSError):
  549. pass
  550. try:
  551. WinError = WindowsError
  552. except NameError:
  553. WinError = PlainWindowsError
  554. if can_read_reg:
  555. HKEY_CLASSES_ROOT = hkey_mod.HKEY_CLASSES_ROOT
  556. HKEY_LOCAL_MACHINE = hkey_mod.HKEY_LOCAL_MACHINE
  557. HKEY_CURRENT_USER = hkey_mod.HKEY_CURRENT_USER
  558. HKEY_USERS = hkey_mod.HKEY_USERS
  559. def RegGetValue(root, key):
  560. """This utility function returns a value in the registry
  561. without having to open the key first. Only available on
  562. Windows platforms with a version of Python that can read the
  563. registry. Returns the same thing as
  564. SCons.Util.RegQueryValueEx, except you just specify the entire
  565. path to the value, and don't have to bother opening the key
  566. first. So:
  567. Instead of:
  568. k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE,
  569. r'SOFTWARE\Microsoft\Windows\CurrentVersion')
  570. out = SCons.Util.RegQueryValueEx(k,
  571. 'ProgramFilesDir')
  572. You can write:
  573. out = SCons.Util.RegGetValue(SCons.Util.HKEY_LOCAL_MACHINE,
  574. r'SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir')
  575. """
  576. # I would use os.path.split here, but it's not a filesystem
  577. # path...
  578. p = key.rfind('\\') + 1
  579. keyp = key[:p-1] # -1 to omit trailing slash
  580. val = key[p:]
  581. k = RegOpenKeyEx(root, keyp)
  582. return RegQueryValueEx(k,val)
  583. else:
  584. HKEY_CLASSES_ROOT = None
  585. HKEY_LOCAL_MACHINE = None
  586. HKEY_CURRENT_USER = None
  587. HKEY_USERS = None
  588. def RegGetValue(root, key):
  589. raise WinError
  590. def RegOpenKeyEx(root, key):
  591. raise WinError
  592. if sys.platform == 'win32':
  593. def WhereIs(file, path=None, pathext=None, reject=[]):
  594. if path is None:
  595. try:
  596. path = os.environ['PATH']
  597. except KeyError:
  598. return None
  599. if is_String(path):
  600. path = path.split(os.pathsep)
  601. if pathext is None:
  602. try:
  603. pathext = os.environ['PATHEXT']
  604. except KeyError:
  605. pathext = '.COM;.EXE;.BAT;.CMD'
  606. if is_String(pathext):
  607. pathext = pathext.split(os.pathsep)
  608. for ext in pathext:
  609. if ext.lower() == file[-len(ext):].lower():
  610. pathext = ['']
  611. break
  612. if not is_List(reject) and not is_Tuple(reject):
  613. reject = [reject]
  614. for dir in path:
  615. f = os.path.join(dir, file)
  616. for ext in pathext:
  617. fext = f + ext
  618. if os.path.isfile(fext):
  619. try:
  620. reject.index(fext)
  621. except ValueError:
  622. return os.path.normpath(fext)
  623. continue
  624. return None
  625. elif os.name == 'os2':
  626. def WhereIs(file, path=None, pathext=None, reject=[]):
  627. if path is None:
  628. try:
  629. path = os.environ['PATH']
  630. except KeyError:
  631. return None
  632. if is_String(path):
  633. path = path.split(os.pathsep)
  634. if pathext is None:
  635. pathext = ['.exe', '.cmd']
  636. for ext in pathext:
  637. if ext.lower() == file[-len(ext):].lower():
  638. pathext = ['']
  639. break
  640. if not is_List(reject) and not is_Tuple(reject):
  641. reject = [reject]
  642. for dir in path:
  643. f = os.path.join(dir, file)
  644. for ext in pathext:
  645. fext = f + ext
  646. if os.path.isfile(fext):
  647. try:
  648. reject.index(fext)
  649. except ValueError:
  650. return os.path.normpath(fext)
  651. continue
  652. return None
  653. else:
  654. def WhereIs(file, path=None, pathext=None, reject=[]):
  655. import stat
  656. if path is None:
  657. try:
  658. path = os.environ['PATH']
  659. except KeyError:
  660. return None
  661. if is_String(path):
  662. path = path.split(os.pathsep)
  663. if not is_List(reject) and not is_Tuple(reject):
  664. reject = [reject]
  665. for d in path:
  666. f = os.path.join(d, file)
  667. if os.path.isfile(f):
  668. try:
  669. st = os.stat(f)
  670. except OSError:
  671. # os.stat() raises OSError, not IOError if the file
  672. # doesn't exist, so in this case we let IOError get
  673. # raised so as to not mask possibly serious disk or
  674. # network issues.
  675. continue
  676. if stat.S_IMODE(st[stat.ST_MODE]) & 0o111:
  677. try:
  678. reject.index(f)
  679. except ValueError:
  680. return os.path.normpath(f)
  681. continue
  682. return None
  683. def PrependPath(oldpath, newpath, sep = os.pathsep,
  684. delete_existing=1, canonicalize=None):
  685. """This prepends newpath elements to the given oldpath. Will only
  686. add any particular path once (leaving the first one it encounters
  687. and ignoring the rest, to preserve path order), and will
  688. os.path.normpath and os.path.normcase all paths to help assure
  689. this. This can also handle the case where the given old path
  690. variable is a list instead of a string, in which case a list will
  691. be returned instead of a string.
  692. Example:
  693. Old Path: "/foo/bar:/foo"
  694. New Path: "/biz/boom:/foo"
  695. Result: "/biz/boom:/foo:/foo/bar"
  696. If delete_existing is 0, then adding a path that exists will
  697. not move it to the beginning; it will stay where it is in the
  698. list.
  699. If canonicalize is not None, it is applied to each element of
  700. newpath before use.
  701. """
  702. orig = oldpath
  703. is_list = 1
  704. paths = orig
  705. if not is_List(orig) and not is_Tuple(orig):
  706. paths = paths.split(sep)
  707. is_list = 0
  708. if is_String(newpath):
  709. newpaths = newpath.split(sep)
  710. elif not is_List(newpath) and not is_Tuple(newpath):
  711. newpaths = [ newpath ] # might be a Dir
  712. else:
  713. newpaths = newpath
  714. if canonicalize:
  715. newpaths=list(map(canonicalize, newpaths))
  716. if not delete_existing:
  717. # First uniquify the old paths, making sure to
  718. # preserve the first instance (in Unix/Linux,
  719. # the first one wins), and remembering them in normpaths.
  720. # Then insert the new paths at the head of the list
  721. # if they're not already in the normpaths list.
  722. result = []
  723. normpaths = []
  724. for path in paths:
  725. if not path:
  726. continue
  727. normpath = os.path.normpath(os.path.normcase(path))
  728. if normpath not in normpaths:
  729. result.append(path)
  730. normpaths.append(normpath)
  731. newpaths.reverse() # since we're inserting at the head
  732. for path in newpaths:
  733. if not path:
  734. continue
  735. normpath = os.path.normpath(os.path.normcase(path))
  736. if normpath not in normpaths:
  737. result.insert(0, path)
  738. normpaths.append(normpath)
  739. paths = result
  740. else:
  741. newpaths = newpaths + paths # prepend new paths
  742. normpaths = []
  743. paths = []
  744. # now we add them only if they are unique
  745. for path in newpaths:
  746. normpath = os.path.normpath(os.path.normcase(path))
  747. if path and not normpath in normpaths:
  748. paths.append(path)
  749. normpaths.append(normpath)
  750. if is_list:
  751. return paths
  752. else:
  753. return sep.join(paths)
  754. def AppendPath(oldpath, newpath, sep = os.pathsep,
  755. delete_existing=1, canonicalize=None):
  756. """This appends new path elements to the given old path. Will
  757. only add any particular path once (leaving the last one it
  758. encounters and ignoring the rest, to preserve path order), and
  759. will os.path.normpath and os.path.normcase all paths to help
  760. assure this. This can also handle the case where the given old
  761. path variable is a list instead of a string, in which case a list
  762. will be returned instead of a string.
  763. Example:
  764. Old Path: "/foo/bar:/foo"
  765. New Path: "/biz/boom:/foo"
  766. Result: "/foo/bar:/biz/boom:/foo"
  767. If delete_existing is 0, then adding a path that exists
  768. will not move it to the end; it will stay where it is in the list.
  769. If canonicalize is not None, it is applied to each element of
  770. newpath before use.
  771. """
  772. orig = oldpath
  773. is_list = 1
  774. paths = orig
  775. if not is_List(orig) and not is_Tuple(orig):
  776. paths = paths.split(sep)
  777. is_list = 0
  778. if is_String(newpath):
  779. newpaths = newpath.split(sep)
  780. elif not is_List(newpath) and not is_Tuple(newpath):
  781. newpaths = [ newpath ] # might be a Dir
  782. else:
  783. newpaths = newpath
  784. if canonicalize:
  785. newpaths=list(map(canonicalize, newpaths))
  786. if not delete_existing:
  787. # add old paths to result, then
  788. # add new paths if not already present
  789. # (I thought about using a dict for normpaths for speed,
  790. # but it's not clear hashing the strings would be faster
  791. # than linear searching these typically short lists.)
  792. result = []
  793. normpaths = []
  794. for path in paths:
  795. if not path:
  796. continue
  797. result.append(path)
  798. normpaths.append(os.path.normpath(os.path.normcase(path)))
  799. for path in newpaths:
  800. if not path:
  801. continue
  802. normpath = os.path.normpath(os.path.normcase(path))
  803. if normpath not in normpaths:
  804. result.append(path)
  805. normpaths.append(normpath)
  806. paths = result
  807. else:
  808. # start w/ new paths, add old ones if not present,
  809. # then reverse.
  810. newpaths = paths + newpaths # append new paths
  811. newpaths.reverse()
  812. normpaths = []
  813. paths = []
  814. # now we add them only if they are unique
  815. for path in newpaths:
  816. normpath = os.path.normpath(os.path.normcase(path))
  817. if path and not normpath in normpaths:
  818. paths.append(path)
  819. normpaths.append(normpath)
  820. paths.reverse()
  821. if is_list:
  822. return paths
  823. else:
  824. return sep.join(paths)
  825. def AddPathIfNotExists(env_dict, key, path, sep=os.pathsep):
  826. """This function will take 'key' out of the dictionary
  827. 'env_dict', then add the path 'path' to that key if it is not
  828. already there. This treats the value of env_dict[key] as if it
  829. has a similar format to the PATH variable...a list of paths
  830. separated by tokens. The 'path' will get added to the list if it
  831. is not already there."""
  832. try:
  833. is_list = 1
  834. paths = env_dict[key]
  835. if not is_List(env_dict[key]):
  836. paths = paths.split(sep)
  837. is_list = 0
  838. if os.path.normcase(path) not in list(map(os.path.normcase, paths)):
  839. paths = [ path ] + paths
  840. if is_list:
  841. env_dict[key] = paths
  842. else:
  843. env_dict[key] = sep.join(paths)
  844. except KeyError:
  845. env_dict[key] = path
  846. if sys.platform == 'cygwin':
  847. def get_native_path(path):
  848. """Transforms an absolute path into a native path for the system. In
  849. Cygwin, this converts from a Cygwin path to a Windows one."""
  850. return os.popen('cygpath -w ' + path).read().replace('\n', '')
  851. else:
  852. def get_native_path(path):
  853. """Transforms an absolute path into a native path for the system.
  854. Non-Cygwin version, just leave the path alone."""
  855. return path
  856. display = DisplayEngine()
  857. def Split(arg):
  858. if is_List(arg) or is_Tuple(arg):
  859. return arg
  860. elif is_String(arg):
  861. return arg.split()
  862. else:
  863. return [arg]
  864. class CLVar(UserList):
  865. """A class for command-line construction variables.
  866. This is a list that uses Split() to split an initial string along
  867. white-space arguments, and similarly to split any strings that get
  868. added. This allows us to Do the Right Thing with Append() and
  869. Prepend() (as well as straight Python foo = env['VAR'] + 'arg1
  870. arg2') regardless of whether a user adds a list or a string to a
  871. command-line construction variable.
  872. """
  873. def __init__(self, seq = []):
  874. UserList.__init__(self, Split(seq))
  875. def __add__(self, other):
  876. return UserList.__add__(self, CLVar(other))
  877. def __radd__(self, other):
  878. return UserList.__radd__(self, CLVar(other))
  879. def __coerce__(self, other):
  880. return (self, CLVar(other))
  881. def __str__(self):
  882. return ' '.join(self.data)
  883. # A dictionary that preserves the order in which items are added.
  884. # Submitted by David Benjamin to ActiveState's Python Cookbook web site:
  885. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747
  886. # Including fixes/enhancements from the follow-on discussions.
  887. class OrderedDict(UserDict):
  888. def __init__(self, dict = None):
  889. self._keys = []
  890. UserDict.__init__(self, dict)
  891. def __delitem__(self, key):
  892. UserDict.__delitem__(self, key)
  893. self._keys.remove(key)
  894. def __setitem__(self, key, item):
  895. UserDict.__setitem__(self, key, item)
  896. if key not in self._keys: self._keys.append(key)
  897. def clear(self):
  898. UserDict.clear(self)
  899. self._keys = []
  900. def copy(self):
  901. dict = OrderedDict()
  902. dict.update(self)
  903. return dict
  904. def items(self):
  905. return list(zip(self._keys, list(self.values())))
  906. def keys(self):
  907. return self._keys[:]
  908. def popitem(self):
  909. try:
  910. key = self._keys[-1]
  911. except IndexError:
  912. raise KeyError('dictionary is empty')
  913. val = self[key]
  914. del self[key]
  915. return (key, val)
  916. def setdefault(self, key, failobj = None):
  917. UserDict.setdefault(self, key, failobj)
  918. if key not in self._keys: self._keys.append(key)
  919. def update(self, dict):
  920. for (key, val) in dict.items():
  921. self.__setitem__(key, val)
  922. def values(self):
  923. return list(map(self.get, self._keys))
  924. class Selector(OrderedDict):
  925. """A callable ordered dictionary that maps file suffixes to
  926. dictionary values. We preserve the order in which items are added
  927. so that get_suffix() calls always return the first suffix added."""
  928. def __call__(self, env, source, ext=None):
  929. if ext is None:
  930. try:
  931. ext = source[0].get_suffix()
  932. except IndexError:
  933. ext = ""
  934. try:
  935. return self[ext]
  936. except KeyError:
  937. # Try to perform Environment substitution on the keys of
  938. # the dictionary before giving up.
  939. s_dict = {}
  940. for (k,v) in self.items():
  941. if k is not None:
  942. s_k = env.subst(k)
  943. if s_k in s_dict:
  944. # We only raise an error when variables point
  945. # to the same suffix. If one suffix is literal
  946. # and a variable suffix contains this literal,
  947. # the literal wins and we don't raise an error.
  948. raise KeyError(s_dict[s_k][0], k, s_k)
  949. s_dict[s_k] = (k,v)
  950. try:
  951. return s_dict[ext][1]
  952. except KeyError:
  953. try:
  954. return self[None]
  955. except KeyError:
  956. return None
  957. if sys.platform == 'cygwin':
  958. # On Cygwin, os.path.normcase() lies, so just report back the
  959. # fact that the underlying Windows OS is case-insensitive.
  960. def case_sensitive_suffixes(s1, s2):
  961. return 0
  962. else:
  963. def case_sensitive_suffixes(s1, s2):
  964. return (os.path.normcase(s1) != os.path.normcase(s2))
  965. def adjustixes(fname, pre, suf, ensure_suffix=False):
  966. if pre:
  967. path, fn = os.path.split(os.path.normpath(fname))
  968. if fn[:len(pre)] != pre:
  969. fname = os.path.join(path, pre + fn)
  970. # Only append a suffix if the suffix we're going to add isn't already
  971. # there, and if either we've been asked to ensure the specific suffix
  972. # is present or there's no suffix on it at all.
  973. if suf and fname[-len(suf):] != suf and \
  974. (ensure_suffix or not splitext(fname)[1]):
  975. fname = fname + suf
  976. return fname
  977. # From Tim Peters,
  978. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
  979. # ASPN: Python Cookbook: Remove duplicates from a sequence
  980. # (Also in the printed Python Cookbook.)
  981. def unique(s):
  982. """Return a list of the elements in s, but without duplicates.
  983. For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3],
  984. unique("abcabc") some permutation of ["a", "b", "c"], and
  985. unique(([1, 2], [2, 3], [1, 2])) some permutation of
  986. [[2, 3], [1, 2]].
  987. For best speed, all sequence elements should be hashable. Then
  988. unique() will usually work in linear time.
  989. If not possible, the sequence elements should enjoy a total
  990. ordering, and if list(s).sort() doesn't raise TypeError it's
  991. assumed that they do enjoy a total ordering. Then unique() will
  992. usually work in O(N*log2(N)) time.
  993. If that's not possible either, the sequence elements must support
  994. equality-testing. Then unique() will usually work in quadratic
  995. time.
  996. """
  997. n = len(s)
  998. if n == 0:
  999. return []
  1000. # Try using a dict first, as that's the fastest and will usually
  1001. # work. If it doesn't work, it will usually fail quickly, so it
  1002. # usually doesn't cost much to *try* it. It requires that all the
  1003. # sequence elements be hashable, and support equality comparison.
  1004. u = {}
  1005. try:
  1006. for x in s:
  1007. u[x] = 1
  1008. except TypeError:
  1009. pass # move on to the next method
  1010. else:
  1011. return list(u.keys())
  1012. del u
  1013. # We can't hash all the elements. Second fastest is to sort,
  1014. # which brings the equal elements together; then duplicates are
  1015. # easy to weed out in a single pass.
  1016. # NOTE: Python's list.sort() was designed to be efficient in the
  1017. # presence of many duplicate elements. This isn't true of all
  1018. # sort functions in all languages or libraries, so this approach
  1019. # is more effective in Python than it may be elsewhere.
  1020. try:
  1021. t = sorted(s)
  1022. except TypeError:
  1023. pass # move on to the next method
  1024. else:
  1025. assert n > 0
  1026. last = t[0]
  1027. lasti = i = 1
  1028. while i < n:
  1029. if t[i] != last:
  1030. t[lasti] = last = t[i]
  1031. lasti = lasti + 1
  1032. i = i + 1
  1033. return t[:lasti]
  1034. del t
  1035. # Brute force is all that's left.
  1036. u = []
  1037. for x in s:
  1038. if x not in u:
  1039. u.append(x)
  1040. return u
  1041. # From Alex Martelli,
  1042. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
  1043. # ASPN: Python Cookbook: Remove duplicates from a sequence
  1044. # First comment, dated 2001/10/13.
  1045. # (Also in the printed Python Cookbook.)
  1046. def uniquer(seq, idfun=None):
  1047. if idfun is None:
  1048. def idfun(x): return x
  1049. seen = {}
  1050. result = []
  1051. for item in seq:
  1052. marker = idfun(item)
  1053. # in old Python versions:
  1054. # if seen.has_key(marker)
  1055. # but in new ones:
  1056. if marker in seen: continue
  1057. seen[marker] = 1
  1058. result.append(item)
  1059. return result
  1060. # A more efficient implementation of Alex's uniquer(), this avoids the
  1061. # idfun() argument and function-call overhead by assuming that all
  1062. # items in the sequence are hashable.
  1063. def uniquer_hashables(seq):
  1064. seen = {}
  1065. result = []
  1066. for item in seq:
  1067. #if not item in seen:
  1068. if item not in seen:
  1069. seen[item] = 1
  1070. result.append(item)
  1071. return result
  1072. # Recipe 19.11 "Reading Lines with Continuation Characters",
  1073. # by Alex Martelli, straight from the Python CookBook (2nd edition).
  1074. def logical_lines(physical_lines, joiner=''.join):
  1075. logical_line = []
  1076. for line in physical_lines:
  1077. stripped = line.rstrip()
  1078. if stripped.endswith('\\'):
  1079. # a line which continues w/the next physical line
  1080. logical_line.append(stripped[:-1])
  1081. else:
  1082. # a line which does not continue, end of logical line
  1083. logical_line.append(line)
  1084. yield joiner(logical_line)
  1085. logical_line = []
  1086. if logical_line:
  1087. # end of sequence implies end of last logical line
  1088. yield joiner(logical_line)
  1089. class LogicalLines(object):
  1090. """ Wrapper class for the logical_lines method.
  1091. Allows us to read all "logical" lines at once from a
  1092. given file object.
  1093. """
  1094. def __init__(self, fileobj):
  1095. self.fileobj = fileobj
  1096. def readlines(self):
  1097. result = [l for l in logical_lines(self.fileobj)]
  1098. return result
  1099. class UniqueList(UserList):
  1100. def __init__(self, seq = []):
  1101. UserList.__init__(self, seq)
  1102. self.unique = True
  1103. def __make_unique(self):
  1104. if not self.unique:
  1105. self.data = uniquer_hashables(self.data)
  1106. self.unique = True
  1107. def __lt__(self, other):
  1108. self.__make_unique()
  1109. return UserList.__lt__(self, other)
  1110. def __le__(self, other):
  1111. self.__make_unique()
  1112. return UserList.__le__(self, other)
  1113. def __eq__(self, other):
  1114. self.__make_unique()
  1115. return UserList.__eq__(self, other)
  1116. def __ne__(self, other):
  1117. self.__make_unique()
  1118. return UserList.__ne__(self, other)
  1119. def __gt__(self, other):
  1120. self.__make_unique()
  1121. return UserList.__gt__(self, other)
  1122. def __ge__(self, other):
  1123. self.__make_unique()
  1124. return UserList.__ge__(self, other)
  1125. def __cmp__(self, other):
  1126. self.__make_unique()
  1127. return UserList.__cmp__(self, other)
  1128. def __len__(self):
  1129. self.__make_unique()
  1130. return UserList.__len__(self)
  1131. def __getitem__(self, i):
  1132. self.__make_unique()
  1133. return UserList.__getitem__(self, i)
  1134. def __setitem__(self, i, item):
  1135. UserList.__setitem__(self, i, item)
  1136. self.unique = False
  1137. def __getslice__(self, i, j):
  1138. self.__make_unique()
  1139. return UserList.__getslice__(self, i, j)
  1140. def __setslice__(self, i, j, other):
  1141. UserList.__setslice__(self, i, j, other)
  1142. self.unique = False
  1143. def __add__(self, other):
  1144. result = UserList.__add__(self, other)
  1145. result.unique = False
  1146. return result
  1147. def __radd__(self, other):
  1148. result = UserList.__radd__(self, other)
  1149. result.unique = False
  1150. return result
  1151. def __iadd__(self, other):
  1152. result = UserList.__iadd__(self, other)
  1153. result.unique = False
  1154. return result
  1155. def __mul__(self, other):
  1156. result = UserList.__mul__(self, other)
  1157. result.unique = False
  1158. return result
  1159. def __rmul__(self, other):
  1160. result = UserList.__rmul__(self, other)
  1161. result.unique = False
  1162. return result
  1163. def __imul__(self, other):
  1164. result = UserList.__imul__(self, other)
  1165. result.unique = False
  1166. return result
  1167. def append(self, item):
  1168. UserList.append(self, item)
  1169. self.unique = False
  1170. def insert(self, i):
  1171. UserList.insert(self, i)
  1172. self.unique = False
  1173. def count(self, item):
  1174. self.__make_unique()
  1175. return UserList.count(self, item)
  1176. def index(self, item):
  1177. self.__make_unique()
  1178. return UserList.index(self, item)
  1179. def reverse(self):
  1180. self.__make_unique()
  1181. UserList.reverse(self)
  1182. def sort(self, *args, **kwds):
  1183. self.__make_unique()
  1184. return UserList.sort(self, *args, **kwds)
  1185. def extend(self, other):
  1186. UserList.extend(self, other)
  1187. self.unique = False
  1188. class Unbuffered(object):
  1189. """
  1190. A proxy class that wraps a file object, flushing after every write,
  1191. and delegating everything else to the wrapped object.
  1192. """
  1193. def __init__(self, file):
  1194. self.file = file
  1195. self.softspace = 0 ## backward compatibility; not supported in Py3k
  1196. def write(self, arg):
  1197. try:
  1198. self.file.write(arg)
  1199. self.file.flush()
  1200. except IOError:
  1201. # Stdout might be connected to a pipe that has been closed
  1202. # by now. The most likely reason for the pipe being closed
  1203. # is that the user has press ctrl-c. It this is the case,
  1204. # then SCons is currently shutdown. We therefore ignore
  1205. # IOError's here so that SCons can continue and shutdown
  1206. # properly so that the .sconsign is correctly written
  1207. # before SCons exits.
  1208. pass
  1209. def __getattr__(self, attr):
  1210. return getattr(self.file, attr)
  1211. def make_path_relative(path):
  1212. """ makes an absolute path name to a relative pathname.
  1213. """
  1214. if os.path.isabs(path):
  1215. drive_s,path = os.path.splitdrive(path)
  1216. import re
  1217. if not drive_s:
  1218. path=re.compile("/*(.*)").findall(path)[0]
  1219. else:
  1220. path=path[1:]
  1221. assert( not os.path.isabs( path ) ), path
  1222. return path
  1223. # The original idea for AddMethod() and RenameFunction() come from the
  1224. # following post to the ActiveState Python Cookbook:
  1225. #
  1226. # ASPN: Python Cookbook : Install bound methods in an instance
  1227. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/223613
  1228. #
  1229. # That code was a little fragile, though, so the following changes
  1230. # have been wrung on it:
  1231. #
  1232. # * Switched the installmethod() "object" and "function" arguments,
  1233. # so the order reflects that the left-hand side is the thing being
  1234. # "assigned to" and the right-hand side is the value being assigned.
  1235. #
  1236. # * Changed explicit type-checking to the "try: klass = object.__class__"
  1237. # block in installmethod() below so that it still works with the
  1238. # old-style classes that SCons uses.
  1239. #
  1240. # * Replaced the by-hand creation of methods and functions with use of
  1241. # the "new" module, as alluded to in Alex Martelli's response to the
  1242. # following Cookbook post:
  1243. #
  1244. # ASPN: Python Cookbook : Dynamically added methods to a class
  1245. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81732
  1246. def AddMethod(obj, function, name=None):
  1247. """
  1248. Adds either a bound method to an instance or the function itself (or an unbound method in Python 2) to a class.
  1249. If name is ommited the name of the specified function
  1250. is used by default.
  1251. Example::
  1252. a = A()
  1253. def f(self, x, y):
  1254. self.z = x + y
  1255. AddMethod(f, A, "add")
  1256. a.add(2, 4)
  1257. print(a.z)
  1258. AddMethod(lambda self, i: self.l[i], a, "listIndex")
  1259. print(a.listIndex(5))
  1260. """
  1261. if name is None:
  1262. name = function.__name__
  1263. else:
  1264. function = RenameFunction(function, name)
  1265. # Note the Python version checks - WLB
  1266. # Python 3.3 dropped the 3rd parameter from types.MethodType
  1267. if hasattr(obj, '__class__') and obj.__class__ is not type:
  1268. # "obj" is an instance, so it gets a bound method.
  1269. if sys.version_info[:2] > (3, 2):
  1270. method = MethodType(function, obj)
  1271. else:
  1272. method = MethodType(function, obj, obj.__class__)
  1273. else:
  1274. # Handle classes
  1275. method = function
  1276. setattr(obj, name, method)
  1277. def RenameFunction(function, name):
  1278. """
  1279. Returns a function identical to the specified function, but with
  1280. the specified name.
  1281. """
  1282. return FunctionType(function.__code__,
  1283. function.__globals__,
  1284. name,
  1285. function.__defaults__)
  1286. md5 = False
  1287. def MD5signature(s):
  1288. return str(s)
  1289. def MD5filesignature(fname, chunksize=65536):
  1290. with open(fname, "rb") as f:
  1291. result = f.read()
  1292. return result
  1293. try:
  1294. import hashlib
  1295. except ImportError:
  1296. pass
  1297. else:
  1298. if hasattr(hashlib, 'md5'):
  1299. md5 = True
  1300. def MD5signature(s):
  1301. m = hashlib.md5()
  1302. try:
  1303. m.update(to_bytes(s))
  1304. except TypeError as e:
  1305. m.update(to_bytes(str(s)))
  1306. return m.hexdigest()
  1307. def MD5filesignature(fname, chunksize=65536):
  1308. m = hashlib.md5()
  1309. f = open(fname, "rb")
  1310. while True:
  1311. blck = f.read(chunksize)
  1312. if not blck:
  1313. break
  1314. m.update(to_bytes(blck))
  1315. f.close()
  1316. return m.hexdigest()
  1317. def MD5collect(signatures):
  1318. """
  1319. Collects a list of signatures into an aggregate signature.
  1320. signatures - a list of signatures
  1321. returns - the aggregate signature
  1322. """
  1323. if len(signatures) == 1:
  1324. return signatures[0]
  1325. else:
  1326. return MD5signature(', '.join(signatures))
  1327. def silent_intern(x):
  1328. """
  1329. Perform sys.intern() on the passed argument and return the result.
  1330. If the input is ineligible (e.g. a unicode string) the original argument is
  1331. returned and no exception is thrown.
  1332. """
  1333. try:
  1334. return sys.intern(x)
  1335. except TypeError:
  1336. return x
  1337. # From Dinu C. Gherman,
  1338. # Python Cookbook, second edition, recipe 6.17, p. 277.
  1339. # Also:
  1340. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205
  1341. # ASPN: Python Cookbook: Null Object Design Pattern
  1342. #TODO??? class Null(object):
  1343. class Null(object):
  1344. """ Null objects always and reliably "do nothing." """
  1345. def __new__(cls, *args, **kwargs):
  1346. if not '_instance' in vars(cls):
  1347. cls._instance = super(Null, cls).__new__(cls, *args, **kwargs)
  1348. return cls._instance
  1349. def __init__(self, *args, **kwargs):
  1350. pass
  1351. def __call__(self, *args, **kwargs):
  1352. return self
  1353. def __repr__(self):
  1354. return "Null(0x%08X)" % id(self)
  1355. def __nonzero__(self):
  1356. return False
  1357. def __bool__(self):
  1358. return False
  1359. def __getattr__(self, name):
  1360. return self
  1361. def __setattr__(self, name, value):
  1362. return self
  1363. def __delattr__(self, name):
  1364. return self
  1365. class NullSeq(Null):
  1366. def __len__(self):
  1367. return 0
  1368. def __iter__(self):
  1369. return iter(())
  1370. def __getitem__(self, i):
  1371. return self
  1372. def __delitem__(self, i):
  1373. return self
  1374. def __setitem__(self, i, v):
  1375. return self
  1376. del __revision__
  1377. def to_bytes (s):
  1378. if isinstance (s, (bytes, bytearray)) or bytes is str:
  1379. return s
  1380. return bytes (s, 'utf-8')
  1381. def to_str (s):
  1382. if bytes is str or is_String(s):
  1383. return s
  1384. return str (s, 'utf-8')
  1385. # Local Variables:
  1386. # tab-width:4
  1387. # indent-tabs-mode:nil
  1388. # End:
  1389. # vim: set expandtab tabstop=4 shiftwidth=4: