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>It boils down to reading input, then</p>

<pre><code>exec &lt;code&gt; in globals,locals
</code></pre>

<p>in an infinite loop.</p>

<p>See e.g. <a href="https://github.com/ipython/ipython/blob/master/IPython/terminal/interactiveshell.py#L444" rel="nofollow"><code>IPython.frontend.terminal.console.interactiveshell.TerminalInteractiveSh
ell.mainloop()</code></a>.</p>

<p>Continuation detection is done in <a href="https://github.com/ipython/ipython/blob/master/IPython/core/inputsplitter.py#L330" rel="nofollow"><code>inputsplitter.push_accepts_more()</code></a> by trying <code>ast.parse()</code>.</p>

<p>Actually, IPython already has an interactive web console called <a href="https://ipython.org/notebook.html" rel="nofollow">Jupyter Notebook</a>, so your best bet should be to reuse it.</p>

python read-eval-print-loop simulate