Simulate Python interactive mode
<p>Im writing a private online Python interpreter for <a href="http://vk.com" rel="nofollow">VK</a>, which would closely simulate IDLE console. Only me and some people in whitelist would be able to use this feature, no unsafe code which can harm my server. But I have a little problem. For example, I send the string with code <code>def foo():</code>, and I dont want to get <code>SyntaxError</code> but continue defining function line by line without writing long strings with use of <code>\n</code>. <code>exec()</code> and <code>eval()</code> doesn't suit me in that case. What should I use to get desired effect? Sorry if duplicate, still dont get it from similar questions. </p>

<p>The Python standard library provides the <a href="https://docs.python.org/2/library/code.html" rel="nofollow"><code>code</code></a> and <a href="https://docs.python.org/2/library/codeop.html" rel="nofollow"><code>codeop</code></a> modules to help you with this. The <code>code</code> module just straight-up simulates the standard interactive interpreter:</p>

<pre><code>import code
code.interact()
</code></pre>

<p>It also provides a few facilities for more detailed control and customization of how it works.</p>

<p>If you want to build things up from more basic components, the <code>codeop</code> module provides a command compiler that remembers <code>__future__</code> statements and recognizes incomplete commands:</p>

<pre><code>import codeop
compiler = codeop.CommandCompiler()

try:
    codeobject = compiler(some_source_string)
    # codeobject is an exec-utable code object if some_source_string was a
    # complete command, or None if the command is incomplete.
except (SyntaxError, OverflowError, ValueError):
    # If some_source_string is invalid, we end up here.
    # OverflowError and ValueError can occur in some cases involving invalid literals.
</code></pre>

python read-eval-print-loop simulate