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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. """Python part of the warnings subsystem."""
  2. import sys, re, types
  3. __all__ = ["warn", "showwarning", "formatwarning", "filterwarnings",
  4. "resetwarnings"]
  5. defaultaction = "default"
  6. filters = []
  7. onceregistry = {}
  8. def warn(message, category=None, stacklevel=1):
  9. """Issue a warning, or maybe ignore it or raise an exception."""
  10. # Check category argument
  11. if category is None:
  12. category = UserWarning
  13. assert issubclass(category, Warning)
  14. # Get context information
  15. try:
  16. caller = sys._getframe(stacklevel)
  17. except ValueError:
  18. globals = sys.__dict__
  19. lineno = 1
  20. else:
  21. globals = caller.f_globals
  22. lineno = caller.f_lineno
  23. module = globals['__name__']
  24. filename = globals.get('__file__')
  25. if filename:
  26. fnl = filename.lower()
  27. if fnl.endswith(".pyc") or fnl.endswith(".pyo"):
  28. filename = filename[:-1]
  29. else:
  30. if module == "__main__":
  31. filename = sys.argv[0]
  32. if not filename:
  33. filename = module
  34. registry = globals.setdefault("__warningregistry__", {})
  35. warn_explicit(message, category, filename, lineno, module, registry)
  36. def warn_explicit(message, category, filename, lineno,
  37. module=None, registry=None):
  38. if module is None:
  39. module = filename
  40. if module[-3:].lower() == ".py":
  41. module = module[:-3] # XXX What about leading pathname?
  42. if registry is None:
  43. registry = {}
  44. key = (message, category, lineno)
  45. # Quick test for common case
  46. if registry.get(key):
  47. return
  48. # Search the filters
  49. for item in filters:
  50. action, msg, cat, mod, ln = item
  51. if (msg.match(message) and
  52. issubclass(category, cat) and
  53. mod.match(module) and
  54. (ln == 0 or lineno == ln)):
  55. break
  56. else:
  57. action = defaultaction
  58. # Early exit actions
  59. if action == "ignore":
  60. registry[key] = 1
  61. return
  62. if action == "error":
  63. raise category(message)
  64. # Other actions
  65. if action == "once":
  66. registry[key] = 1
  67. oncekey = (message, category)
  68. if onceregistry.get(oncekey):
  69. return
  70. onceregistry[oncekey] = 1
  71. elif action == "always":
  72. pass
  73. elif action == "module":
  74. registry[key] = 1
  75. altkey = (message, category, 0)
  76. if registry.get(altkey):
  77. return
  78. registry[altkey] = 1
  79. elif action == "default":
  80. registry[key] = 1
  81. else:
  82. # Unrecognized actions are errors
  83. raise RuntimeError(
  84. "Unrecognized action (%s) in warnings.filters:\n %s" %
  85. (`action`, str(item)))
  86. # Print message and context
  87. showwarning(message, category, filename, lineno)
  88. def showwarning(message, category, filename, lineno, file=None):
  89. """Hook to write a warning to a file; replace if you like."""
  90. if file is None:
  91. file = sys.stderr
  92. file.write(formatwarning(message, category, filename, lineno))
  93. def formatwarning(message, category, filename, lineno):
  94. """Function to format a warning the standard way."""
  95. import linecache
  96. s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message)
  97. line = linecache.getline(filename, lineno).strip()
  98. if line:
  99. s = s + " " + line + "\n"
  100. return s
  101. def filterwarnings(action, message="", category=Warning, module="", lineno=0,
  102. append=0):
  103. """Insert an entry into the list of warnings filters (at the front).
  104. Use assertions to check that all arguments have the right type."""
  105. assert action in ("error", "ignore", "always", "default", "module",
  106. "once"), "invalid action: %s" % `action`
  107. assert isinstance(message, types.StringType), "message must be a string"
  108. assert isinstance(category, types.ClassType), "category must be a class"
  109. assert issubclass(category, Warning), "category must be a Warning subclass"
  110. assert type(module) is types.StringType, "module must be a string"
  111. assert type(lineno) is types.IntType and lineno >= 0, \
  112. "lineno must be an int >= 0"
  113. item = (action, re.compile(message, re.I), category,
  114. re.compile(module), lineno)
  115. if append:
  116. filters.append(item)
  117. else:
  118. filters.insert(0, item)
  119. def resetwarnings():
  120. """Reset the list of warnings filters to its default state."""
  121. filters[:] = []
  122. class _OptionError(Exception):
  123. """Exception used by option processing helpers."""
  124. pass
  125. # Helper to process -W options passed via sys.warnoptions
  126. def _processoptions(args):
  127. for arg in args:
  128. try:
  129. _setoption(arg)
  130. except _OptionError, msg:
  131. print >>sys.stderr, "Invalid -W option ignored:", msg
  132. # Helper for _processoptions()
  133. def _setoption(arg):
  134. parts = arg.split(':')
  135. if len(parts) > 5:
  136. raise _OptionError("too many fields (max 5): %s" % `arg`)
  137. while len(parts) < 5:
  138. parts.append('')
  139. action, message, category, module, lineno = [s.strip()
  140. for s in parts]
  141. action = _getaction(action)
  142. message = re.escape(message)
  143. category = _getcategory(category)
  144. module = re.escape(module)
  145. if module:
  146. module = module + '$'
  147. if lineno:
  148. try:
  149. lineno = int(lineno)
  150. if lineno < 0:
  151. raise ValueError
  152. except (ValueError, OverflowError):
  153. raise _OptionError("invalid lineno %s" % `lineno`)
  154. else:
  155. lineno = 0
  156. filterwarnings(action, message, category, module, lineno)
  157. # Helper for _setoption()
  158. def _getaction(action):
  159. if not action:
  160. return "default"
  161. if action == "all": return "always" # Alias
  162. for a in ['default', 'always', 'ignore', 'module', 'once', 'error']:
  163. if a.startswith(action):
  164. return a
  165. raise _OptionError("invalid action: %s" % `action`)
  166. # Helper for _setoption()
  167. def _getcategory(category):
  168. if not category:
  169. return Warning
  170. if re.match("^[a-zA-Z0-9_]+$", category):
  171. try:
  172. cat = eval(category)
  173. except NameError:
  174. raise _OptionError("unknown warning category: %s" % `category`)
  175. else:
  176. i = category.rfind(".")
  177. module = category[:i]
  178. klass = category[i+1:]
  179. try:
  180. m = __import__(module, None, None, [klass])
  181. except ImportError:
  182. raise _OptionError("invalid module name: %s" % `module`)
  183. try:
  184. cat = getattr(m, klass)
  185. except AttributeError:
  186. raise _OptionError("unknown warning category: %s" % `category`)
  187. if (not isinstance(cat, types.ClassType) or
  188. not issubclass(cat, Warning)):
  189. raise _OptionError("invalid warning category: %s" % `category`)
  190. return cat
  191. # Self-test
  192. def _test():
  193. import getopt
  194. testoptions = []
  195. try:
  196. opts, args = getopt.getopt(sys.argv[1:], "W:")
  197. except getopt.error, msg:
  198. print >>sys.stderr, msg
  199. return
  200. for o, a in opts:
  201. testoptions.append(a)
  202. try:
  203. _processoptions(testoptions)
  204. except _OptionError, msg:
  205. print >>sys.stderr, msg
  206. return
  207. for item in filters: print item
  208. hello = "hello world"
  209. warn(hello); warn(hello); warn(hello); warn(hello)
  210. warn(hello, UserWarning)
  211. warn(hello, DeprecationWarning)
  212. for i in range(3):
  213. warn(hello)
  214. filterwarnings("error", "", Warning, "", 0)
  215. try:
  216. warn(hello)
  217. except Exception, msg:
  218. print "Caught", msg.__class__.__name__ + ":", msg
  219. else:
  220. print "No exception"
  221. resetwarnings()
  222. try:
  223. filterwarnings("booh", "", Warning, "", 0)
  224. except Exception, msg:
  225. print "Caught", msg.__class__.__name__ + ":", msg
  226. else:
  227. print "No exception"
  228. # Module initialization
  229. if __name__ == "__main__":
  230. import __main__
  231. sys.modules['warnings'] = __main__
  232. _test()
  233. else:
  234. _processoptions(sys.warnoptions)