Team Ai
Apppublic

parthtamu/rag-code-assistant

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
code.html558 linesDownload Raw Back to docs
1<!DOCTYPE html>2 3<html lang="en" data-content_root="../">4  <head>5    <meta charset="utf-8" />6    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />7<meta property="og:title" content="code — Interpreter base classes" />8<meta property="og:type" content="website" />9<meta property="og:url" content="https://docs.python.org/3/library/code.html" />10<meta property="og:site_name" content="Python documentation" />11<meta property="og:description" content="Source code: Lib/code.py The code module provides facilities to implement read-eval-print loops in Python. Two classes and convenience functions are included which can be used to build applications..." />12<meta property="og:image:width" content="1146" />13<meta property="og:image:height" content="600" />14<meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_code_4c055f5c.png" />15<meta property="og:image:alt" content="Source code: Lib/code.py The code module provides facilities to implement read-eval-print loops in Python. Two classes and convenience functions are included which can be used to build applications..." />16<meta name="description" content="Source code: Lib/code.py The code module provides facilities to implement read-eval-print loops in Python. Two classes and convenience functions are included which can be used to build applications..." />17<meta name="twitter:card" content="summary_large_image" />18<meta name="theme-color" content="#3776ab">19 20    <title>code — Interpreter base classes &#8212; Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">21    22    <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />23    <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" />24    <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" />25    <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" />26    <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />27    28    <script src="../_static/documentation_options.js?v=6b7c9ff5"></script>29    <script src="../_static/doctools.js?v=9bcbadda"></script>30    <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>31    <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script>32    33    <script src="../_static/sidebar.js"></script>34    35    <link rel="search" type="application/opensearchdescription+xml"36          title="Search within Python 3.15.0a6 documentation"37          href="../_static/opensearch.xml"/>38    <link rel="author" title="About these documents" href="../about.html" />39    <link rel="index" title="Index" href="../genindex.html" />40    <link rel="search" title="Search" href="../search.html" />41    <link rel="copyright" title="Copyright" href="../copyright.html" />42    <link rel="next" title="codeop — Compile Python code" href="codeop.html" />43    <link rel="prev" title="Custom Python Interpreters" href="custominterp.html" />44    45      46      <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script>47      48      <link rel="canonical" href="https://docs.python.org/3/library/code.html">49      50    51 52    53    <style>54      @media only screen {55        table.full-width-table {56            width: 100%;57        }58      }59    </style>60<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">61    <link rel="shortcut icon" type="image/png" href="../_static/py.svg">62            <script type="text/javascript" src="../_static/copybutton.js"></script>63            <script type="text/javascript" src="../_static/menu.js"></script>64            <script type="text/javascript" src="../_static/search-focus.js"></script>65            <script type="text/javascript" src="../_static/themetoggle.js"></script> 66            <script type="text/javascript" src="../_static/rtd_switcher.js"></script>67            <meta name="readthedocs-addons-api-version" content="1">68 69  </head>70<body>71<div class="mobile-nav">72    <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"73           aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu">74    <nav class="nav-content" role="navigation">75        <label for="menuToggler" class="toggler__label">76            <span></span>77        </label>78        <span class="nav-items-wrapper">79            <a href="https://www.python.org/" class="nav-logo">80                <img src="../_static/py.svg" alt="Python logo">81            </a>82            <span class="version_switcher_placeholder"></span>83            <form role="search" class="search" action="../search.html" method="get">84                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">85                    <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>86                </svg>87                <input placeholder="Quick search" aria-label="Quick search" type="search" name="q">88                <input type="submit" value="Go">89            </form>90        </span>91    </nav>92    <div class="menu-wrapper">93        <nav class="menu" role="navigation" aria-label="main navigation">94            <div class="language_switcher_placeholder"></div>95            96<label class="theme-selector-label">97    Theme98    <select class="theme-selector" oninput="activateTheme(this.value)">99        <option value="auto" selected>Auto</option>100        <option value="light">Light</option>101        <option value="dark">Dark</option>102    </select>103</label>104  <div>105    <h3><a href="../contents.html">Table of Contents</a></h3>106    <ul>107<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">code</span></code> — Interpreter base classes</a><ul>108<li><a class="reference internal" href="#interactive-interpreter-objects">Interactive Interpreter Objects</a></li>109<li><a class="reference internal" href="#interactive-console-objects">Interactive Console Objects</a></li>110</ul>111</li>112</ul>113 114  </div>115  <div>116    <h4>Previous topic</h4>117    <p class="topless"><a href="custominterp.html"118                          title="previous chapter">Custom Python Interpreters</a></p>119  </div>120  <div>121    <h4>Next topic</h4>122    <p class="topless"><a href="codeop.html"123                          title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">codeop</span></code> — Compile Python code</a></p>124  </div>125  <script>126    document.addEventListener('DOMContentLoaded', () => {127        const title = document.querySelector('meta[property="og:title"]').content;128        const elements = document.querySelectorAll('.improvepage');129        const pageurl = window.location.href.split('?')[0];130        elements.forEach(element => {131            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));132            url.searchParams.set('pagetitle', title);133            url.searchParams.set('pageurl', pageurl);134            url.searchParams.set('pagesource', "library/code.rst");135            element.href = url.toString();136        });137    });138  </script>139  <div role="note" aria-label="source link">140    <h3>This page</h3>141    <ul class="this-page-menu">142      <li><a href="../bugs.html">Report a bug</a></li>143      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>144      <li>145        <a href="https://github.com/python/cpython/blob/main/Doc/library/code.rst?plain=1"146            rel="nofollow">Show source147        </a>148      </li>149      150    </ul>151  </div>152        </nav>153    </div>154</div>155 156  157    <div class="related" role="navigation" aria-label="Related">158      <h3>Navigation</h3>159      <ul>160        <li class="right" style="margin-right: 10px">161          <a href="../genindex.html" title="General Index"162             accesskey="I">index</a></li>163        <li class="right" >164          <a href="../py-modindex.html" title="Python Module Index"165             >modules</a> |</li>166        <li class="right" >167          <a href="codeop.html" title="codeop — Compile Python code"168             accesskey="N">next</a> |</li>169        <li class="right" >170          <a href="custominterp.html" title="Custom Python Interpreters"171             accesskey="P">previous</a> |</li>172 173          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>174          <li><a href="https://www.python.org/">Python</a> &#187;</li>175          <li class="switchers">176            <div class="language_switcher_placeholder"></div>177            <div class="version_switcher_placeholder"></div>178          </li>179          <li>180              181          </li>182    <li id="cpython-language-and-version">183      <a href="../index.html">3.15.0a6 Documentation</a> &#187;184    </li>185 186          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>187          <li class="nav-item nav-item-2"><a href="custominterp.html" accesskey="U">Custom Python Interpreters</a> &#187;</li>188        <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">code</span></code> — Interpreter base classes</a></li>189                <li class="right">190                    191 192    <div class="inline-search" role="search">193        <form class="inline-search" action="../search.html" method="get">194          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">195          <input type="submit" value="Go">196        </form>197    </div>198                     |199                </li>200            <li class="right">201<label class="theme-selector-label">202    Theme203    <select class="theme-selector" oninput="activateTheme(this.value)">204        <option value="auto" selected>Auto</option>205        <option value="light">Light</option>206        <option value="dark">Dark</option>207    </select>208</label> |</li>209            210      </ul>211    </div>    212 213    <div class="document">214      <div class="documentwrapper">215        <div class="bodywrapper">216          <div class="body" role="main">217            218  <section id="module-code">219<span id="code-interpreter-base-classes"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">code</span></code> — Interpreter base classes<a class="headerlink" href="#module-code" title="Link to this heading">¶</a></h1>220<p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/code.py">Lib/code.py</a></p>221<hr class="docutils" />222<p>The <code class="docutils literal notranslate"><span class="pre">code</span></code> module provides facilities to implement read-eval-print loops in223Python.  Two classes and convenience functions are included which can be used to224build applications which provide an interactive interpreter prompt.</p>225<dl class="py class">226<dt class="sig sig-object py" id="code.InteractiveInterpreter">227<em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">code.</span></span><span class="sig-name descname"><span class="pre">InteractiveInterpreter</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">locals</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveInterpreter" title="Link to this definition">¶</a></dt>228<dd><p>This class deals with parsing and interpreter state (the user’s namespace); it229does not deal with input buffering or prompting or input file naming (the230filename is always passed in explicitly). The optional <em>locals</em> argument231specifies a mapping to use as the namespace in which code will be executed;232it defaults to a newly created dictionary with key <code class="docutils literal notranslate"><span class="pre">'__name__'</span></code> set to233<code class="docutils literal notranslate"><span class="pre">'__console__'</span></code> and key <code class="docutils literal notranslate"><span class="pre">'__doc__'</span></code> set to <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>234<p>Note that functions and classes objects created under an235<code class="xref py py-class docutils literal notranslate"><span class="pre">InteractiveInterpreter</span></code> instance will belong to the namespace236specified by <em>locals</em>.237They are only pickleable if <em>locals</em> is the namespace of an existing238module.</p>239</dd></dl>240 241<dl class="py class">242<dt class="sig sig-object py" id="code.InteractiveConsole">243<em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">code.</span></span><span class="sig-name descname"><span class="pre">InteractiveConsole</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">locals</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">filename</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'&lt;console&gt;'</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">local_exit</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveConsole" title="Link to this definition">¶</a></dt>244<dd><p>Closely emulate the behavior of the interactive Python interpreter. This class245builds on <a class="reference internal" href="#code.InteractiveInterpreter" title="code.InteractiveInterpreter"><code class="xref py py-class docutils literal notranslate"><span class="pre">InteractiveInterpreter</span></code></a> and adds prompting using the familiar246<code class="docutils literal notranslate"><span class="pre">sys.ps1</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.ps2</span></code>, and input buffering. If <em>local_exit</em> is true,247<code class="docutils literal notranslate"><span class="pre">exit()</span></code> and <code class="docutils literal notranslate"><span class="pre">quit()</span></code> in the console will not raise <a class="reference internal" href="exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a>, but248instead return to the calling code.</p>249<div class="versionchanged">250<p><span class="versionmodified changed">Changed in version 3.13: </span>Added <em>local_exit</em> parameter.</p>251</div>252</dd></dl>253 254<dl class="py function">255<dt class="sig sig-object py" id="code.interact">256<span class="sig-prename descclassname"><span class="pre">code.</span></span><span class="sig-name descname"><span class="pre">interact</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">banner</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">readfunc</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">local</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">exitmsg</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">local_exit</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#code.interact" title="Link to this definition">¶</a></dt>257<dd><p>Convenience function to run a read-eval-print loop.  This creates a new258instance of <a class="reference internal" href="#code.InteractiveConsole" title="code.InteractiveConsole"><code class="xref py py-class docutils literal notranslate"><span class="pre">InteractiveConsole</span></code></a> and sets <em>readfunc</em> to be used as259the <a class="reference internal" href="#code.InteractiveConsole.raw_input" title="code.InteractiveConsole.raw_input"><code class="xref py py-meth docutils literal notranslate"><span class="pre">InteractiveConsole.raw_input()</span></code></a> method, if provided.  If <em>local</em> is260provided, it is passed to the <code class="xref py py-class docutils literal notranslate"><span class="pre">InteractiveConsole</span></code> constructor for261use as the default namespace for the interpreter loop.  If <em>local_exit</em> is provided,262it is passed to the <code class="xref py py-class docutils literal notranslate"><span class="pre">InteractiveConsole</span></code> constructor.  The <a class="reference internal" href="#code.InteractiveConsole.interact" title="code.InteractiveConsole.interact"><code class="xref py py-meth docutils literal notranslate"><span class="pre">interact()</span></code></a>263method of the instance is then run with <em>banner</em> and <em>exitmsg</em> passed as the264banner and exit message to use, if provided.  The console object is discarded265after use.</p>266<div class="versionchanged">267<p><span class="versionmodified changed">Changed in version 3.6: </span>Added <em>exitmsg</em> parameter.</p>268</div>269<div class="versionchanged">270<p><span class="versionmodified changed">Changed in version 3.13: </span>Added <em>local_exit</em> parameter.</p>271</div>272</dd></dl>273 274<dl class="py function">275<dt class="sig sig-object py" id="code.compile_command">276<span class="sig-prename descclassname"><span class="pre">code.</span></span><span class="sig-name descname"><span class="pre">compile_command</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">source</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">filename</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'&lt;input&gt;'</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">symbol</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'single'</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#code.compile_command" title="Link to this definition">¶</a></dt>277<dd><p>This function is useful for programs that want to emulate Python’s interpreter278main loop (a.k.a. the read-eval-print loop).  The tricky part is to determine279when the user has entered an incomplete command that can be completed by280entering more text (as opposed to a complete command or a syntax error).  This281function <em>almost</em> always makes the same decision as the real interpreter main282loop.</p>283<p><em>source</em> is the source string; <em>filename</em> is the optional filename from which284source was read, defaulting to <code class="docutils literal notranslate"><span class="pre">'&lt;input&gt;'</span></code>; and <em>symbol</em> is the optional285grammar start symbol, which should be <code class="docutils literal notranslate"><span class="pre">'single'</span></code> (the default), <code class="docutils literal notranslate"><span class="pre">'eval'</span></code>286or <code class="docutils literal notranslate"><span class="pre">'exec'</span></code>.</p>287<p>Returns a code object (the same as <code class="docutils literal notranslate"><span class="pre">compile(source,</span> <span class="pre">filename,</span> <span class="pre">symbol)</span></code>) if the288command is complete and valid; <code class="docutils literal notranslate"><span class="pre">None</span></code> if the command is incomplete; raises289<a class="reference internal" href="exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> if the command is complete and contains a syntax error, or290raises <a class="reference internal" href="exceptions.html#OverflowError" title="OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> or <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if the command contains an291invalid literal.</p>292</dd></dl>293 294<section id="interactive-interpreter-objects">295<span id="interpreter-objects"></span><h2>Interactive Interpreter Objects<a class="headerlink" href="#interactive-interpreter-objects" title="Link to this heading">¶</a></h2>296<dl class="py method">297<dt class="sig sig-object py" id="code.InteractiveInterpreter.runsource">298<span class="sig-prename descclassname"><span class="pre">InteractiveInterpreter.</span></span><span class="sig-name descname"><span class="pre">runsource</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">source</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">filename</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'&lt;input&gt;'</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">symbol</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'single'</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveInterpreter.runsource" title="Link to this definition">¶</a></dt>299<dd><p>Compile and run some source in the interpreter. Arguments are the same as for300<a class="reference internal" href="#code.compile_command" title="code.compile_command"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile_command()</span></code></a>; the default for <em>filename</em> is <code class="docutils literal notranslate"><span class="pre">'&lt;input&gt;'</span></code>, and for301<em>symbol</em> is <code class="docutils literal notranslate"><span class="pre">'single'</span></code>.  One of several things can happen:</p>302<ul class="simple">303<li><p>The input is incorrect; <a class="reference internal" href="#code.compile_command" title="code.compile_command"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile_command()</span></code></a> raised an exception304(<a class="reference internal" href="exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> or <a class="reference internal" href="exceptions.html#OverflowError" title="OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>).  A syntax traceback will be305printed by calling the <a class="reference internal" href="#code.InteractiveInterpreter.showsyntaxerror" title="code.InteractiveInterpreter.showsyntaxerror"><code class="xref py py-meth docutils literal notranslate"><span class="pre">showsyntaxerror()</span></code></a> method.  <code class="xref py py-meth docutils literal notranslate"><span class="pre">runsource()</span></code>306returns <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p></li>307<li><p>The input is incomplete, and more input is required; <a class="reference internal" href="#code.compile_command" title="code.compile_command"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile_command()</span></code></a>308returned <code class="docutils literal notranslate"><span class="pre">None</span></code>. <code class="xref py py-meth docutils literal notranslate"><span class="pre">runsource()</span></code> returns <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p></li>309<li><p>The input is complete; <a class="reference internal" href="#code.compile_command" title="code.compile_command"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile_command()</span></code></a> returned a code object.  The310code is executed by calling the <a class="reference internal" href="#code.InteractiveInterpreter.runcode" title="code.InteractiveInterpreter.runcode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">runcode()</span></code></a> (which also handles run-time311exceptions, except for <a class="reference internal" href="exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a>). <code class="xref py py-meth docutils literal notranslate"><span class="pre">runsource()</span></code> returns <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p></li>312</ul>313<p>The return value can be used to decide whether to use <code class="docutils literal notranslate"><span class="pre">sys.ps1</span></code> or <code class="docutils literal notranslate"><span class="pre">sys.ps2</span></code>314to prompt the next line.</p>315</dd></dl>316 317<dl class="py method">318<dt class="sig sig-object py" id="code.InteractiveInterpreter.runcode">319<span class="sig-prename descclassname"><span class="pre">InteractiveInterpreter.</span></span><span class="sig-name descname"><span class="pre">runcode</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">code</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveInterpreter.runcode" title="Link to this definition">¶</a></dt>320<dd><p>Execute a code object. When an exception occurs, <a class="reference internal" href="#code.InteractiveInterpreter.showtraceback" title="code.InteractiveInterpreter.showtraceback"><code class="xref py py-meth docutils literal notranslate"><span class="pre">showtraceback()</span></code></a> is called321to display a traceback.  All exceptions are caught except <a class="reference internal" href="exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a>,322which is allowed to propagate.</p>323<p>A note about <a class="reference internal" href="exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a>: this exception may occur elsewhere in324this code, and may not always be caught.  The caller should be prepared to deal325with it.</p>326</dd></dl>327 328<dl class="py method">329<dt class="sig sig-object py" id="code.InteractiveInterpreter.showsyntaxerror">330<span class="sig-prename descclassname"><span class="pre">InteractiveInterpreter.</span></span><span class="sig-name descname"><span class="pre">showsyntaxerror</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">filename</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveInterpreter.showsyntaxerror" title="Link to this definition">¶</a></dt>331<dd><p>Display the syntax error that just occurred.  This does not display a stack332trace because there isn’t one for syntax errors. If <em>filename</em> is given, it is333stuffed into the exception instead of the default filename provided by Python’s334parser, because it always uses <code class="docutils literal notranslate"><span class="pre">'&lt;string&gt;'</span></code> when reading from a string. The335output is written by the <a class="reference internal" href="#code.InteractiveInterpreter.write" title="code.InteractiveInterpreter.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code></a> method.</p>336</dd></dl>337 338<dl class="py method">339<dt class="sig sig-object py" id="code.InteractiveInterpreter.showtraceback">340<span class="sig-prename descclassname"><span class="pre">InteractiveInterpreter.</span></span><span class="sig-name descname"><span class="pre">showtraceback</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveInterpreter.showtraceback" title="Link to this definition">¶</a></dt>341<dd><p>Display the exception that just occurred.  We remove the first stack item342because it is within the interpreter object implementation. The output is343written by the <a class="reference internal" href="#code.InteractiveInterpreter.write" title="code.InteractiveInterpreter.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code></a> method.</p>344<div class="versionchanged">345<p><span class="versionmodified changed">Changed in version 3.5: </span>The full chained traceback is displayed instead346of just the primary traceback.</p>347</div>348</dd></dl>349 350<dl class="py method">351<dt class="sig sig-object py" id="code.InteractiveInterpreter.write">352<span class="sig-prename descclassname"><span class="pre">InteractiveInterpreter.</span></span><span class="sig-name descname"><span class="pre">write</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">data</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveInterpreter.write" title="Link to this definition">¶</a></dt>353<dd><p>Write a string to the standard error stream (<code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>). Derived classes354should override this to provide the appropriate output handling as needed.</p>355</dd></dl>356 357</section>358<section id="interactive-console-objects">359<span id="console-objects"></span><h2>Interactive Console Objects<a class="headerlink" href="#interactive-console-objects" title="Link to this heading">¶</a></h2>360<p>The <a class="reference internal" href="#code.InteractiveConsole" title="code.InteractiveConsole"><code class="xref py py-class docutils literal notranslate"><span class="pre">InteractiveConsole</span></code></a> class is a subclass of361<a class="reference internal" href="#code.InteractiveInterpreter" title="code.InteractiveInterpreter"><code class="xref py py-class docutils literal notranslate"><span class="pre">InteractiveInterpreter</span></code></a>, and so offers all the methods of the362interpreter objects as well as the following additions.</p>363<dl class="py method">364<dt class="sig sig-object py" id="code.InteractiveConsole.interact">365<span class="sig-prename descclassname"><span class="pre">InteractiveConsole.</span></span><span class="sig-name descname"><span class="pre">interact</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">banner</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">exitmsg</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveConsole.interact" title="Link to this definition">¶</a></dt>366<dd><p>Closely emulate the interactive Python console. The optional <em>banner</em> argument367specify the banner to print before the first interaction; by default it prints a368banner similar to the one printed by the standard Python interpreter, followed369by the class name of the console object in parentheses (so as not to confuse370this with the real interpreter – since it’s so close!).</p>371<p>The optional <em>exitmsg</em> argument specifies an exit message printed when exiting.372Pass the empty string to suppress the exit message. If <em>exitmsg</em> is not given or373<code class="docutils literal notranslate"><span class="pre">None</span></code>, a default message is printed.</p>374<div class="versionchanged">375<p><span class="versionmodified changed">Changed in version 3.4: </span>To suppress printing any banner, pass an empty string.</p>376</div>377<div class="versionchanged">378<p><span class="versionmodified changed">Changed in version 3.6: </span>Print an exit message when exiting.</p>379</div>380</dd></dl>381 382<dl class="py method">383<dt class="sig sig-object py" id="code.InteractiveConsole.push">384<span class="sig-prename descclassname"><span class="pre">InteractiveConsole.</span></span><span class="sig-name descname"><span class="pre">push</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">line</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveConsole.push" title="Link to this definition">¶</a></dt>385<dd><p>Push a line of source text to the interpreter. The line should not have a386trailing newline; it may have internal newlines.  The line is appended to a387buffer and the interpreter’s <a class="reference internal" href="#code.InteractiveInterpreter.runsource" title="code.InteractiveInterpreter.runsource"><code class="xref py py-meth docutils literal notranslate"><span class="pre">runsource()</span></code></a> method is called with the388concatenated contents of the buffer as source.  If this indicates that the389command was executed or invalid, the buffer is reset; otherwise, the command is390incomplete, and the buffer is left as it was after the line was appended.  The391return value is <code class="docutils literal notranslate"><span class="pre">True</span></code> if more input is required, <code class="docutils literal notranslate"><span class="pre">False</span></code> if the line was392dealt with in some way (this is the same as <code class="xref py py-meth docutils literal notranslate"><span class="pre">runsource()</span></code>).</p>393</dd></dl>394 395<dl class="py method">396<dt class="sig sig-object py" id="code.InteractiveConsole.resetbuffer">397<span class="sig-prename descclassname"><span class="pre">InteractiveConsole.</span></span><span class="sig-name descname"><span class="pre">resetbuffer</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveConsole.resetbuffer" title="Link to this definition">¶</a></dt>398<dd><p>Remove any unhandled source text from the input buffer.</p>399</dd></dl>400 401<dl class="py method">402<dt class="sig sig-object py" id="code.InteractiveConsole.raw_input">403<span class="sig-prename descclassname"><span class="pre">InteractiveConsole.</span></span><span class="sig-name descname"><span class="pre">raw_input</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">prompt</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">''</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveConsole.raw_input" title="Link to this definition">¶</a></dt>404<dd><p>Write a prompt and read a line.  The returned line does not include the trailing405newline.  When the user enters the EOF key sequence, <a class="reference internal" href="exceptions.html#EOFError" title="EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> is raised.406The base implementation reads from <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code>; a subclass may replace this407with a different implementation.</p>408</dd></dl>409 410</section>411</section>412 413 414            <div class="clearer"></div>415          </div>416        </div>417      </div>418      <div class="sphinxsidebar" role="navigation" aria-label="Main">419        <div class="sphinxsidebarwrapper">420  <div>421    <h3><a href="../contents.html">Table of Contents</a></h3>422    <ul>423<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">code</span></code> — Interpreter base classes</a><ul>424<li><a class="reference internal" href="#interactive-interpreter-objects">Interactive Interpreter Objects</a></li>425<li><a class="reference internal" href="#interactive-console-objects">Interactive Console Objects</a></li>426</ul>427</li>428</ul>429 430  </div>431  <div>432    <h4>Previous topic</h4>433    <p class="topless"><a href="custominterp.html"434                          title="previous chapter">Custom Python Interpreters</a></p>435  </div>436  <div>437    <h4>Next topic</h4>438    <p class="topless"><a href="codeop.html"439                          title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">codeop</span></code> — Compile Python code</a></p>440  </div>441  <script>442    document.addEventListener('DOMContentLoaded', () => {443        const title = document.querySelector('meta[property="og:title"]').content;444        const elements = document.querySelectorAll('.improvepage');445        const pageurl = window.location.href.split('?')[0];446        elements.forEach(element => {447            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));448            url.searchParams.set('pagetitle', title);449            url.searchParams.set('pageurl', pageurl);450            url.searchParams.set('pagesource', "library/code.rst");451            element.href = url.toString();452        });453    });454  </script>455  <div role="note" aria-label="source link">456    <h3>This page</h3>457    <ul class="this-page-menu">458      <li><a href="../bugs.html">Report a bug</a></li>459      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>460      <li>461        <a href="https://github.com/python/cpython/blob/main/Doc/library/code.rst?plain=1"462            rel="nofollow">Show source463        </a>464      </li>465      466    </ul>467  </div>468        </div>469<div id="sidebarbutton" title="Collapse sidebar">470<span>«</span>471</div>472 473      </div>474      <div class="clearer"></div>475    </div>  476    <div class="related" role="navigation" aria-label="Related">477      <h3>Navigation</h3>478      <ul>479        <li class="right" style="margin-right: 10px">480          <a href="../genindex.html" title="General Index"481             >index</a></li>482        <li class="right" >483          <a href="../py-modindex.html" title="Python Module Index"484             >modules</a> |</li>485        <li class="right" >486          <a href="codeop.html" title="codeop — Compile Python code"487             >next</a> |</li>488        <li class="right" >489          <a href="custominterp.html" title="Custom Python Interpreters"490             >previous</a> |</li>491 492          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>493          <li><a href="https://www.python.org/">Python</a> &#187;</li>494          <li class="switchers">495            <div class="language_switcher_placeholder"></div>496            <div class="version_switcher_placeholder"></div>497          </li>498          <li>499              500          </li>501    <li id="cpython-language-and-version">502      <a href="../index.html">3.15.0a6 Documentation</a> &#187;503    </li>504 505          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>506          <li class="nav-item nav-item-2"><a href="custominterp.html" >Custom Python Interpreters</a> &#187;</li>507        <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">code</span></code> — Interpreter base classes</a></li>508                <li class="right">509                    510 511    <div class="inline-search" role="search">512        <form class="inline-search" action="../search.html" method="get">513          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">514          <input type="submit" value="Go">515        </form>516    </div>517                     |518                </li>519            <li class="right">520<label class="theme-selector-label">521    Theme522    <select class="theme-selector" oninput="activateTheme(this.value)">523        <option value="auto" selected>Auto</option>524        <option value="light">Light</option>525        <option value="dark">Dark</option>526    </select>527</label> |</li>528            529      </ul>530    </div>  531    <div class="footer">532    &copy; <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation.533    <br>534    This page is licensed under the Python Software Foundation License Version 2.535    <br>536    Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.537    <br>538    539      See <a href="/license.html">History and License</a> for more information.<br>540    541    542    <br>543 544    The Python Software Foundation is a non-profit corporation.545<a href="https://www.python.org/psf/donations/">Please donate.</a>546<br>547    <br>548      Last updated on Mar 10, 2026 (08:58 UTC).549    550      <a href="/bugs.html">Found a bug</a>?551    552    <br>553 554    Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.555    </div>556 557  </body>558</html>