<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>traceback – Extract, format, and print exceptions and stack traces. — Python Module of the Week</title> <link rel="stylesheet" href="../_static/sphinxdoc.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '1.132', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <link rel="author" title="About these documents" href="../about.html" /> <link rel="top" title="Python Module of the Week" href="../index.html" /> <link rel="up" title="Python Runtime Services" href="../runtime_services.html" /> <link rel="next" title="warnings – Non-fatal alerts" href="../warnings/index.html" /> <link rel="prev" title="sysconfig – Interpreter Compile-time Configuration" href="../sysconfig/index.html" /> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="../warnings/index.html" title="warnings – Non-fatal alerts" accesskey="N">next</a> |</li> <li class="right" > <a href="../sysconfig/index.html" title="sysconfig – Interpreter Compile-time Configuration" accesskey="P">previous</a> |</li> <li><a href="../contents.html">PyMOTW</a> »</li> <li><a href="../runtime_services.html" accesskey="U">Python Runtime Services</a> »</li> </ul> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <h3><a href="../contents.html">Table Of Contents</a></h3> <ul> <li><a class="reference internal" href="#">traceback – Extract, format, and print exceptions and stack traces.</a><ul> <li><a class="reference internal" href="#supporting-functions">Supporting Functions</a></li> <li><a class="reference internal" href="#working-with-exceptions">Working With Exceptions</a></li> <li><a class="reference internal" href="#working-with-the-stack">Working With the Stack</a><ul> <li><a class="reference internal" href="#print-stack">print_stack()</a></li> <li><a class="reference internal" href="#format-stack">format_stack()</a></li> <li><a class="reference internal" href="#extract-stack">extract_stack()</a></li> </ul> </li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="../sysconfig/index.html" title="previous chapter">sysconfig – Interpreter Compile-time Configuration</a></p> <h4>Next topic</h4> <p class="topless"><a href="../warnings/index.html" title="next chapter">warnings – Non-fatal alerts</a></p> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/traceback/index.txt" rel="nofollow">Show Source</a></li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <input type="text" name="q" size="18" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <div class="section" id="module-traceback"> <span id="traceback-extract-format-and-print-exceptions-and-stack-traces"></span><h1>traceback – Extract, format, and print exceptions and stack traces.<a class="headerlink" href="#module-traceback" title="Permalink to this headline">¶</a></h1> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field"><th class="field-name">Purpose:</th><td class="field-body">Extract, format, and print exceptions and stack traces.</td> </tr> <tr class="field"><th class="field-name">Python Version:</th><td class="field-body">1.4 and later, with modifications over time</td> </tr> </tbody> </table> <p>The <a class="reference internal" href="#module-traceback" title="traceback: Extract, format, and print exceptions and stack traces."><tt class="xref py py-mod docutils literal"><span class="pre">traceback</span></tt></a> module works with the call stack to produce error messages. A traceback is a stack trace from the point of an exception handler down the call chain to the point where the exception was raised. You can also work with the current call stack up from the point of a call (and without the context of an error), which is useful for finding out the paths being followed into a function.</p> <p>The functions in <a class="reference internal" href="#module-traceback" title="traceback: Extract, format, and print exceptions and stack traces."><tt class="xref py py-mod docutils literal"><span class="pre">traceback</span></tt></a> fall into several common categories. There are functions for extracting raw tracebacks from the current runtime environment (either an exception handler for a traceback, or the regular stack). The extracted stack trace is a sequence of tuples containing the filename, line number, function name, and text of the source line.</p> <p>Once extracted, the stack trace can be formatted using functions like <tt class="xref py py-func docutils literal"><span class="pre">format_exception()</span></tt>, <tt class="xref py py-func docutils literal"><span class="pre">format_stack()</span></tt>, etc. The format functions return a list of strings with messages formatted to be printed. There are shorthand functions for printing the formatted values, as well.</p> <p>Although the functions in <a class="reference internal" href="#module-traceback" title="traceback: Extract, format, and print exceptions and stack traces."><tt class="xref py py-mod docutils literal"><span class="pre">traceback</span></tt></a> mimic the behavior of the interactive interpreter by default, they also are useful for handling exceptions in situations where dumping the full stack trace to stderr is not desirable. For example, a web application may need to format the traceback so it looks good in HTML. An IDE may convert the elements of the stack trace into a clickable list that lets the user browse the source.</p> <div class="section" id="supporting-functions"> <h2>Supporting Functions<a class="headerlink" href="#supporting-functions" title="Permalink to this headline">¶</a></h2> <p>The examples below use the module traceback_example.py (provided in the source package for PyMOTW). The contents are:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">traceback</span> <span class="kn">import</span> <span class="nn">sys</span> <span class="k">def</span> <span class="nf">produce_exception</span><span class="p">(</span><span class="n">recursion_level</span><span class="o">=</span><span class="mi">2</span><span class="p">):</span> <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">flush</span><span class="p">()</span> <span class="k">if</span> <span class="n">recursion_level</span><span class="p">:</span> <span class="n">produce_exception</span><span class="p">(</span><span class="n">recursion_level</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">()</span> <span class="k">def</span> <span class="nf">call_function</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">recursion_level</span><span class="o">=</span><span class="mi">2</span><span class="p">):</span> <span class="k">if</span> <span class="n">recursion_level</span><span class="p">:</span> <span class="k">return</span> <span class="n">call_function</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">recursion_level</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="n">f</span><span class="p">()</span> </pre></div> </div> </div> <div class="section" id="working-with-exceptions"> <h2>Working With Exceptions<a class="headerlink" href="#working-with-exceptions" title="Permalink to this headline">¶</a></h2> <p>The simplest way to handle exception reporting is with <tt class="xref py py-func docutils literal"><span class="pre">print_exc()</span></tt>. It uses <tt class="xref py py-func docutils literal"><span class="pre">sys.exc_info()</span></tt> to obtain the exception information for the current thread, formats the results, and prints the text to a file handle (<tt class="docutils literal"><span class="pre">sys.stderr</span></tt>, by default).</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">traceback</span> <span class="kn">import</span> <span class="nn">sys</span> <span class="kn">from</span> <span class="nn">traceback_example</span> <span class="kn">import</span> <span class="n">produce_exception</span> <span class="k">print</span> <span class="s">'print_exc() with no exception:'</span> <span class="n">traceback</span><span class="o">.</span><span class="n">print_exc</span><span class="p">(</span><span class="nb">file</span><span class="o">=</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">)</span> <span class="k">print</span> <span class="k">try</span><span class="p">:</span> <span class="n">produce_exception</span><span class="p">()</span> <span class="k">except</span> <span class="ne">Exception</span><span class="p">,</span> <span class="n">err</span><span class="p">:</span> <span class="k">print</span> <span class="s">'print_exc():'</span> <span class="n">traceback</span><span class="o">.</span><span class="n">print_exc</span><span class="p">(</span><span class="nb">file</span><span class="o">=</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">)</span> <span class="k">print</span> <span class="k">print</span> <span class="s">'print_exc(1):'</span> <span class="n">traceback</span><span class="o">.</span><span class="n">print_exc</span><span class="p">(</span><span class="n">limit</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="nb">file</span><span class="o">=</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">)</span> </pre></div> </div> <p>In this example, the file handle for <tt class="docutils literal"><span class="pre">sys.stdout</span></tt> is substituted so the informational and traceback messages are mingled correctly:</p> <div class="highlight-python"><pre>$ python traceback_print_exc.py print_exc() with no exception: None print_exc(): Traceback (most recent call last): File "traceback_print_exc.py", line 20, in <module> produce_exception() File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 16, in produce_exception produce_exception(recursion_level-1) File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 16, in produce_exception produce_exception(recursion_level-1) File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 18, in produce_exception raise RuntimeError() RuntimeError print_exc(1): Traceback (most recent call last): File "traceback_print_exc.py", line 20, in <module> produce_exception() RuntimeError</pre> </div> <p><tt class="docutils literal"><span class="pre">print_exc()</span></tt> is just a shortcut for <tt class="xref py py-func docutils literal"><span class="pre">print_exception()</span></tt>, which requires explicit arguments:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">traceback</span> <span class="kn">import</span> <span class="nn">sys</span> <span class="kn">from</span> <span class="nn">traceback_example</span> <span class="kn">import</span> <span class="n">produce_exception</span> <span class="k">try</span><span class="p">:</span> <span class="n">produce_exception</span><span class="p">()</span> <span class="k">except</span> <span class="ne">Exception</span><span class="p">,</span> <span class="n">err</span><span class="p">:</span> <span class="k">print</span> <span class="s">'print_exception():'</span> <span class="n">exc_type</span><span class="p">,</span> <span class="n">exc_value</span><span class="p">,</span> <span class="n">exc_tb</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">exc_info</span><span class="p">()</span> <span class="n">traceback</span><span class="o">.</span><span class="n">print_exception</span><span class="p">(</span><span class="n">exc_type</span><span class="p">,</span> <span class="n">exc_value</span><span class="p">,</span> <span class="n">exc_tb</span><span class="p">)</span> </pre></div> </div> <div class="highlight-python"><pre>$ python traceback_print_exception.py Traceback (most recent call last): File "traceback_print_exception.py", line 16, in <module> produce_exception() File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 16, in produce_exception produce_exception(recursion_level-1) File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 16, in produce_exception produce_exception(recursion_level-1) File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 18, in produce_exception raise RuntimeError() RuntimeError print_exception():</pre> </div> <p>And <tt class="xref py py-func docutils literal"><span class="pre">print_exception()</span></tt> uses <tt class="xref py py-func docutils literal"><span class="pre">format_exception()</span></tt>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">traceback</span> <span class="kn">import</span> <span class="nn">sys</span> <span class="kn">from</span> <span class="nn">pprint</span> <span class="kn">import</span> <span class="n">pprint</span> <span class="kn">from</span> <span class="nn">traceback_example</span> <span class="kn">import</span> <span class="n">produce_exception</span> <span class="k">try</span><span class="p">:</span> <span class="n">produce_exception</span><span class="p">()</span> <span class="k">except</span> <span class="ne">Exception</span><span class="p">,</span> <span class="n">err</span><span class="p">:</span> <span class="k">print</span> <span class="s">'format_exception():'</span> <span class="n">exc_type</span><span class="p">,</span> <span class="n">exc_value</span><span class="p">,</span> <span class="n">exc_tb</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">exc_info</span><span class="p">()</span> <span class="n">pprint</span><span class="p">(</span><span class="n">traceback</span><span class="o">.</span><span class="n">format_exception</span><span class="p">(</span><span class="n">exc_type</span><span class="p">,</span> <span class="n">exc_value</span><span class="p">,</span> <span class="n">exc_tb</span><span class="p">))</span> </pre></div> </div> <div class="highlight-python"><pre>$ python traceback_format_exception.py format_exception(): ['Traceback (most recent call last):\n', ' File "traceback_format_exception.py", line 17, in <module>\n produce_exception()\n', ' File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 16, in produce_exception\n produce_exception(recursion_level-1)\n', ' File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 16, in produce_exception\n produce_exception(recursion_level-1)\n', ' File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 18, in produce_exception\n raise RuntimeError()\n', 'RuntimeError\n']</pre> </div> </div> <div class="section" id="working-with-the-stack"> <h2>Working With the Stack<a class="headerlink" href="#working-with-the-stack" title="Permalink to this headline">¶</a></h2> <p>There are a similar set of functions for performing the same operations with the current call stack instead of a traceback.</p> <div class="section" id="print-stack"> <h3>print_stack()<a class="headerlink" href="#print-stack" title="Permalink to this headline">¶</a></h3> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">traceback</span> <span class="kn">import</span> <span class="nn">sys</span> <span class="kn">from</span> <span class="nn">traceback_example</span> <span class="kn">import</span> <span class="n">call_function</span> <span class="k">def</span> <span class="nf">f</span><span class="p">():</span> <span class="n">traceback</span><span class="o">.</span><span class="n">print_stack</span><span class="p">(</span><span class="nb">file</span><span class="o">=</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">)</span> <span class="k">print</span> <span class="s">'Calling f() directly:'</span> <span class="n">f</span><span class="p">()</span> <span class="k">print</span> <span class="k">print</span> <span class="s">'Calling f() from 3 levels deep:'</span> <span class="n">call_function</span><span class="p">(</span><span class="n">f</span><span class="p">)</span> </pre></div> </div> <div class="highlight-python"><pre>$ python traceback_print_stack.py Calling f() directly: File "traceback_print_stack.py", line 19, in <module> f() File "traceback_print_stack.py", line 16, in f traceback.print_stack(file=sys.stdout) Calling f() from 3 levels deep: File "traceback_print_stack.py", line 23, in <module> call_function(f) File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 22, in call_function return call_function(f, recursion_level-1) File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 22, in call_function return call_function(f, recursion_level-1) File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 24, in call_function return f() File "traceback_print_stack.py", line 16, in f traceback.print_stack(file=sys.stdout)</pre> </div> </div> <div class="section" id="format-stack"> <h3>format_stack()<a class="headerlink" href="#format-stack" title="Permalink to this headline">¶</a></h3> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">traceback</span> <span class="kn">import</span> <span class="nn">sys</span> <span class="kn">from</span> <span class="nn">pprint</span> <span class="kn">import</span> <span class="n">pprint</span> <span class="kn">from</span> <span class="nn">traceback_example</span> <span class="kn">import</span> <span class="n">call_function</span> <span class="k">def</span> <span class="nf">f</span><span class="p">():</span> <span class="k">return</span> <span class="n">traceback</span><span class="o">.</span><span class="n">format_stack</span><span class="p">()</span> <span class="n">formatted_stack</span> <span class="o">=</span> <span class="n">call_function</span><span class="p">(</span><span class="n">f</span><span class="p">)</span> <span class="n">pprint</span><span class="p">(</span><span class="n">formatted_stack</span><span class="p">)</span> </pre></div> </div> <div class="highlight-python"><pre>$ python traceback_format_stack.py [' File "traceback_format_stack.py", line 19, in <module>\n formatted_stack = call_function(f)\n', ' File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 22, in call_function\n return call_function(f, recursion_level-1)\n', ' File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 22, in call_function\n return call_function(f, recursion_level-1)\n', ' File "/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py", line 24, in call_function\n return f()\n', ' File "traceback_format_stack.py", line 17, in f\n return traceback.format_stack()\n']</pre> </div> </div> <div class="section" id="extract-stack"> <h3>extract_stack()<a class="headerlink" href="#extract-stack" title="Permalink to this headline">¶</a></h3> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">traceback</span> <span class="kn">import</span> <span class="nn">sys</span> <span class="kn">from</span> <span class="nn">pprint</span> <span class="kn">import</span> <span class="n">pprint</span> <span class="kn">from</span> <span class="nn">traceback_example</span> <span class="kn">import</span> <span class="n">call_function</span> <span class="k">def</span> <span class="nf">f</span><span class="p">():</span> <span class="k">return</span> <span class="n">traceback</span><span class="o">.</span><span class="n">extract_stack</span><span class="p">()</span> <span class="n">stack</span> <span class="o">=</span> <span class="n">call_function</span><span class="p">(</span><span class="n">f</span><span class="p">)</span> <span class="n">pprint</span><span class="p">(</span><span class="n">stack</span><span class="p">)</span> </pre></div> </div> <div class="highlight-python"><pre>$ python traceback_extract_stack.py [('traceback_extract_stack.py', 19, '<module>', 'stack = call_function(f)'), ('/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py', 22, 'call_function', 'return call_function(f, recursion_level-1)'), ('/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py', 22, 'call_function', 'return call_function(f, recursion_level-1)'), ('/Users/dhellmann/Documents/PyMOTW/src/PyMOTW/traceback/traceback_example.py', 24, 'call_function', 'return f()'), ('traceback_extract_stack.py', 17, 'f', 'return traceback.extract_stack()')]</pre> </div> <div class="admonition-see-also admonition seealso"> <p class="first admonition-title">See also</p> <dl class="last docutils"> <dt><a class="reference external" href="http://docs.python.org/lib/module-traceback.html">traceback</a></dt> <dd>Standard library documentation for this module.</dd> <dt><a class="reference internal" href="../sys/index.html#module-sys" title="sys: System-specific configuration"><tt class="xref py py-mod docutils literal"><span class="pre">sys</span></tt></a></dt> <dd>The sys module includes singletons that hold the current exception.</dd> <dt><a class="reference internal" href="../inspect/index.html#module-inspect" title="inspect: Inspect live objects"><tt class="xref py py-mod docutils literal"><span class="pre">inspect</span></tt></a></dt> <dd>The inspect module includes other functions for probing the frames on the stack.</dd> <dt><a class="reference internal" href="../cgitb/index.html#module-cgitb" title="cgitb: Mis-named module that provides extended traceback information."><tt class="xref py py-mod docutils literal"><span class="pre">cgitb</span></tt></a></dt> <dd>Another module for formatting tracebacks nicely.</dd> </dl> </div> </div> </div> </div> </div> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="../warnings/index.html" title="warnings – Non-fatal alerts" >next</a> |</li> <li class="right" > <a href="../sysconfig/index.html" title="sysconfig – Interpreter Compile-time Configuration" >previous</a> |</li> <li><a href="../contents.html">PyMOTW</a> »</li> <li><a href="../runtime_services.html" >Python Runtime Services</a> »</li> </ul> </div> <div class="footer"> © Copyright Doug Hellmann. Last updated on Oct 24, 2010. Created using <a href="http://sphinx.pocoo.org/">Sphinx</a>. <br/><a href="http://creativecommons.org/licenses/by-nc-sa/3.0/us/" rel="license"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-nc-sa/3.0/us/88x31.png"/></a> </div> </body> </html>