How to get a python script to invoke "python -i" when called normally?
<p>I have a python script that I like to run with <code>python -i script.py</code>, which runs the script and then enters interactive mode so that I can play around with the results.</p>

<p>Is it possible to have the script itself invoke this option, such that I can just run <code>python script.py</code> and the script will enter interactive mode after running?</p>

<p>Of course, I can simply add the <code>-i</code>, or if that is too much effort, I can write a shell script to invoke this.</p>

<p>You could use an instance of <a href="https://docs.python.org/3/library/code.html#code.InteractiveInterpreter" rel="nofollow"><code>code.InteractiveConsole</code></a> to get this to work:</p>

<pre><code>from code import InteractiveConsole
i = 20
d = 30
InteractiveConsole(locals=locals()).interact()
</code></pre>

<p>running this with <code>python script.py</code> will launch an interactive interpreter as the final statement and make the local names defined visible via <code>locals=locals()</code>.</p>

<pre><code>&gt;&gt;&gt; i
20
</code></pre>

<p>Similarly, a convenience function named <a href="https://docs.python.org/3/library/code.html#code.interact" rel="nofollow"><code>code.interact</code></a> can be used:</p>

<pre><code>from code import interact
i = 20
d = 30
interact(local=locals())
</code></pre>

<p>This creates the instance for you, with the only caveat that <code>locals</code> is named <code>local</code> instead.</p>

<hr>

<p>In addition to this, as <a href="http://stackoverflow.com/users/464744/blender">@Blender</a> stated in the comments, you could also embed the <code>IPython</code> REPL by using:</p>

<pre><code>import IPython
IPython.embed()
</code></pre>

<p>which has the added benefit of not requiring the namespace that has been populated in your script to be passed with <code>locals</code>.</p>

python python-interactive