PageRenderTime 135ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/warnings.py

https://gitlab.com/envieidoc/Clover
Python | 404 lines | 384 code | 7 blank | 13 comment | 9 complexity | 356026e66dfe963955a637573569b734 MD5 | raw file
  1. """Python part of the warnings subsystem."""
  2. # Note: function level imports should *not* be used
  3. # in this module as it may cause import lock deadlock.
  4. # See bug 683658.
  5. import linecache
  6. import sys
  7. import types
  8. __all__ = ["warn", "warn_explicit", "showwarning",
  9. "formatwarning", "filterwarnings", "simplefilter",
  10. "resetwarnings", "catch_warnings"]
  11. def warnpy3k(message, category=None, stacklevel=1):
  12. """Issue a deprecation warning for Python 3.x related changes.
  13. Warnings are omitted unless Python is started with the -3 option.
  14. """
  15. if sys.py3kwarning:
  16. if category is None:
  17. category = DeprecationWarning
  18. warn(message, category, stacklevel+1)
  19. def _show_warning(message, category, filename, lineno, file=None, line=None):
  20. """Hook to write a warning to a file; replace if you like."""
  21. if file is None:
  22. file = sys.stderr
  23. if file is None:
  24. # sys.stderr is None - warnings get lost
  25. return
  26. try:
  27. file.write(formatwarning(message, category, filename, lineno, line))
  28. except IOError:
  29. pass # the file (probably stderr) is invalid - this warning gets lost.
  30. # Keep a working version around in case the deprecation of the old API is
  31. # triggered.
  32. showwarning = _show_warning
  33. def formatwarning(message, category, filename, lineno, line=None):
  34. """Function to format a warning the standard way."""
  35. s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message)
  36. line = linecache.getline(filename, lineno) if line is None else line
  37. if line:
  38. line = line.strip()
  39. s += " %s\n" % line
  40. return s
  41. def filterwarnings(action, message="", category=Warning, module="", lineno=0,
  42. append=0):
  43. """Insert an entry into the list of warnings filters (at the front).
  44. 'action' -- one of "error", "ignore", "always", "default", "module",
  45. or "once"
  46. 'message' -- a regex that the warning message must match
  47. 'category' -- a class that the warning must be a subclass of
  48. 'module' -- a regex that the module name must match
  49. 'lineno' -- an integer line number, 0 matches all warnings
  50. 'append' -- if true, append to the list of filters
  51. """
  52. import re
  53. assert action in ("error", "ignore", "always", "default", "module",
  54. "once"), "invalid action: %r" % (action,)
  55. assert isinstance(message, basestring), "message must be a string"
  56. assert isinstance(category, (type, types.ClassType)), \
  57. "category must be a class"
  58. assert issubclass(category, Warning), "category must be a Warning subclass"
  59. assert isinstance(module, basestring), "module must be a string"
  60. assert isinstance(lineno, int) and lineno >= 0, \
  61. "lineno must be an int >= 0"
  62. item = (action, re.compile(message, re.I), category,
  63. re.compile(module), lineno)
  64. if append:
  65. filters.append(item)
  66. else:
  67. filters.insert(0, item)
  68. def simplefilter(action, category=Warning, lineno=0, append=0):
  69. """Insert a simple entry into the list of warnings filters (at the front).
  70. A simple filter matches all modules and messages.
  71. 'action' -- one of "error", "ignore", "always", "default", "module",
  72. or "once"
  73. 'category' -- a class that the warning must be a subclass of
  74. 'lineno' -- an integer line number, 0 matches all warnings
  75. 'append' -- if true, append to the list of filters
  76. """
  77. assert action in ("error", "ignore", "always", "default", "module",
  78. "once"), "invalid action: %r" % (action,)
  79. assert isinstance(lineno, int) and lineno >= 0, \
  80. "lineno must be an int >= 0"
  81. item = (action, None, category, None, lineno)
  82. if append:
  83. filters.append(item)
  84. else:
  85. filters.insert(0, item)
  86. def resetwarnings():
  87. """Clear the list of warning filters, so that no filters are active."""
  88. filters[:] = []
  89. class _OptionError(Exception):
  90. """Exception used by option processing helpers."""
  91. pass
  92. # Helper to process -W options passed via sys.warnoptions
  93. def _processoptions(args):
  94. for arg in args:
  95. try:
  96. _setoption(arg)
  97. except _OptionError, msg:
  98. print >>sys.stderr, "Invalid -W option ignored:", msg
  99. # Helper for _processoptions()
  100. def _setoption(arg):
  101. import re
  102. parts = arg.split(':')
  103. if len(parts) > 5:
  104. raise _OptionError("too many fields (max 5): %r" % (arg,))
  105. while len(parts) < 5:
  106. parts.append('')
  107. action, message, category, module, lineno = [s.strip()
  108. for s in parts]
  109. action = _getaction(action)
  110. message = re.escape(message)
  111. category = _getcategory(category)
  112. module = re.escape(module)
  113. if module:
  114. module = module + '$'
  115. if lineno:
  116. try:
  117. lineno = int(lineno)
  118. if lineno < 0:
  119. raise ValueError
  120. except (ValueError, OverflowError):
  121. raise _OptionError("invalid lineno %r" % (lineno,))
  122. else:
  123. lineno = 0
  124. filterwarnings(action, message, category, module, lineno)
  125. # Helper for _setoption()
  126. def _getaction(action):
  127. if not action:
  128. return "default"
  129. if action == "all": return "always" # Alias
  130. for a in ('default', 'always', 'ignore', 'module', 'once', 'error'):
  131. if a.startswith(action):
  132. return a
  133. raise _OptionError("invalid action: %r" % (action,))
  134. # Helper for _setoption()
  135. def _getcategory(category):
  136. import re
  137. if not category:
  138. return Warning
  139. if re.match("^[a-zA-Z0-9_]+$", category):
  140. try:
  141. cat = eval(category)
  142. except NameError:
  143. raise _OptionError("unknown warning category: %r" % (category,))
  144. else:
  145. i = category.rfind(".")
  146. module = category[:i]
  147. klass = category[i+1:]
  148. try:
  149. m = __import__(module, None, None, [klass])
  150. except ImportError:
  151. raise _OptionError("invalid module name: %r" % (module,))
  152. try:
  153. cat = getattr(m, klass)
  154. except AttributeError:
  155. raise _OptionError("unknown warning category: %r" % (category,))
  156. if not issubclass(cat, Warning):
  157. raise _OptionError("invalid warning category: %r" % (category,))
  158. return cat
  159. # Code typically replaced by _warnings
  160. def warn(message, category=None, stacklevel=1):
  161. """Issue a warning, or maybe ignore it or raise an exception."""
  162. # Check if message is already a Warning object
  163. if isinstance(message, Warning):
  164. category = message.__class__
  165. # Check category argument
  166. if category is None:
  167. category = UserWarning
  168. assert issubclass(category, Warning)
  169. # Get context information
  170. try:
  171. caller = sys._getframe(stacklevel)
  172. except ValueError:
  173. globals = sys.__dict__
  174. lineno = 1
  175. else:
  176. globals = caller.f_globals
  177. lineno = caller.f_lineno
  178. if '__name__' in globals:
  179. module = globals['__name__']
  180. else:
  181. module = "<string>"
  182. filename = globals.get('__file__')
  183. if filename:
  184. fnl = filename.lower()
  185. if fnl.endswith((".pyc", ".pyo")):
  186. filename = filename[:-1]
  187. else:
  188. if module == "__main__":
  189. try:
  190. filename = sys.argv[0]
  191. except AttributeError:
  192. # embedded interpreters don't have sys.argv, see bug #839151
  193. filename = '__main__'
  194. if not filename:
  195. filename = module
  196. registry = globals.setdefault("__warningregistry__", {})
  197. warn_explicit(message, category, filename, lineno, module, registry,
  198. globals)
  199. def warn_explicit(message, category, filename, lineno,
  200. module=None, registry=None, module_globals=None):
  201. lineno = int(lineno)
  202. if module is None:
  203. module = filename or "<unknown>"
  204. if module[-3:].lower() == ".py":
  205. module = module[:-3] # XXX What about leading pathname?
  206. if registry is None:
  207. registry = {}
  208. if isinstance(message, Warning):
  209. text = str(message)
  210. category = message.__class__
  211. else:
  212. text = message
  213. message = category(message)
  214. key = (text, category, lineno)
  215. # Quick test for common case
  216. if registry.get(key):
  217. return
  218. # Search the filters
  219. for item in filters:
  220. action, msg, cat, mod, ln = item
  221. if ((msg is None or msg.match(text)) and
  222. issubclass(category, cat) and
  223. (mod is None or mod.match(module)) and
  224. (ln == 0 or lineno == ln)):
  225. break
  226. else:
  227. action = defaultaction
  228. # Early exit actions
  229. if action == "ignore":
  230. registry[key] = 1
  231. return
  232. # Prime the linecache for formatting, in case the
  233. # "file" is actually in a zipfile or something.
  234. linecache.getlines(filename, module_globals)
  235. if action == "error":
  236. raise message
  237. # Other actions
  238. if action == "once":
  239. registry[key] = 1
  240. oncekey = (text, category)
  241. if onceregistry.get(oncekey):
  242. return
  243. onceregistry[oncekey] = 1
  244. elif action == "always":
  245. pass
  246. elif action == "module":
  247. registry[key] = 1
  248. altkey = (text, category, 0)
  249. if registry.get(altkey):
  250. return
  251. registry[altkey] = 1
  252. elif action == "default":
  253. registry[key] = 1
  254. else:
  255. # Unrecognized actions are errors
  256. raise RuntimeError(
  257. "Unrecognized action (%r) in warnings.filters:\n %s" %
  258. (action, item))
  259. # Print message and context
  260. showwarning(message, category, filename, lineno)
  261. class WarningMessage(object):
  262. """Holds the result of a single showwarning() call."""
  263. _WARNING_DETAILS = ("message", "category", "filename", "lineno", "file",
  264. "line")
  265. def __init__(self, message, category, filename, lineno, file=None,
  266. line=None):
  267. local_values = locals()
  268. for attr in self._WARNING_DETAILS:
  269. setattr(self, attr, local_values[attr])
  270. self._category_name = category.__name__ if category else None
  271. def __str__(self):
  272. return ("{message : %r, category : %r, filename : %r, lineno : %s, "
  273. "line : %r}" % (self.message, self._category_name,
  274. self.filename, self.lineno, self.line))
  275. class catch_warnings(object):
  276. """A context manager that copies and restores the warnings filter upon
  277. exiting the context.
  278. The 'record' argument specifies whether warnings should be captured by a
  279. custom implementation of warnings.showwarning() and be appended to a list
  280. returned by the context manager. Otherwise None is returned by the context
  281. manager. The objects appended to the list are arguments whose attributes
  282. mirror the arguments to showwarning().
  283. The 'module' argument is to specify an alternative module to the module
  284. named 'warnings' and imported under that name. This argument is only useful
  285. when testing the warnings module itself.
  286. """
  287. def __init__(self, record=False, module=None):
  288. """Specify whether to record warnings and if an alternative module
  289. should be used other than sys.modules['warnings'].
  290. For compatibility with Python 3.0, please consider all arguments to be
  291. keyword-only.
  292. """
  293. self._record = record
  294. self._module = sys.modules['warnings'] if module is None else module
  295. self._entered = False
  296. def __repr__(self):
  297. args = []
  298. if self._record:
  299. args.append("record=True")
  300. if self._module is not sys.modules['warnings']:
  301. args.append("module=%r" % self._module)
  302. name = type(self).__name__
  303. return "%s(%s)" % (name, ", ".join(args))
  304. def __enter__(self):
  305. if self._entered:
  306. raise RuntimeError("Cannot enter %r twice" % self)
  307. self._entered = True
  308. self._filters = self._module.filters
  309. self._module.filters = self._filters[:]
  310. self._showwarning = self._module.showwarning
  311. if self._record:
  312. log = []
  313. def showwarning(*args, **kwargs):
  314. log.append(WarningMessage(*args, **kwargs))
  315. self._module.showwarning = showwarning
  316. return log
  317. else:
  318. return None
  319. def __exit__(self, *exc_info):
  320. if not self._entered:
  321. raise RuntimeError("Cannot exit %r without entering first" % self)
  322. self._module.filters = self._filters
  323. self._module.showwarning = self._showwarning
  324. # filters contains a sequence of filter 5-tuples
  325. # The components of the 5-tuple are:
  326. # - an action: error, ignore, always, default, module, or once
  327. # - a compiled regex that must match the warning message
  328. # - a class representing the warning category
  329. # - a compiled regex that must match the module that is being warned
  330. # - a line number for the line being warning, or 0 to mean any line
  331. # If either if the compiled regexs are None, match anything.
  332. _warnings_defaults = False
  333. try:
  334. from _warnings import (filters, default_action, once_registry,
  335. warn, warn_explicit)
  336. defaultaction = default_action
  337. onceregistry = once_registry
  338. _warnings_defaults = True
  339. except ImportError:
  340. filters = []
  341. defaultaction = "default"
  342. onceregistry = {}
  343. # Module initialization
  344. _processoptions(sys.warnoptions)
  345. if not _warnings_defaults:
  346. silence = [ImportWarning, PendingDeprecationWarning]
  347. # Don't silence DeprecationWarning if -3 or -Q was used.
  348. if not sys.py3kwarning and not sys.flags.division_warning:
  349. silence.append(DeprecationWarning)
  350. for cls in silence:
  351. simplefilter("ignore", category=cls)
  352. bytes_warning = sys.flags.bytes_warning
  353. if bytes_warning > 1:
  354. bytes_action = "error"
  355. elif bytes_warning:
  356. bytes_action = "default"
  357. else:
  358. bytes_action = "ignore"
  359. simplefilter(bytes_action, category=BytesWarning, append=1)
  360. del _warnings_defaults