How to coroutine IPython <-> a callback()
<p>In an IPython terminal, I want a function deep in <code>main()</code>
to go back to IPython, where I can print, set ... as usual, then keep running <code>main()</code>:</p>

<pre><code>IPython
    run main.py
    ...
    def callback( *args ):
        ...
        try:
            back_to_ipython()  # &lt;-- how to do this ?
                In[]: print, set *args ...
                ...
        except KeyboardInterrupt:  # or IPython magic
            pass

        return  # from callback(), keep running main()
</code></pre>

<p>This must run in python2.</p>

<p>(The name <code>callback</code> could be <code>anything</code>, but my use case is scipy.optimize -> callback.
Perhaps some clever scipy person has done this ?)</p>

<p><hr>
Added Tuesday 11 Oct: thanks for <code>embed</code>,
but it seems to run into a bug, or my misunderstanding:</p>

<pre><code># http://stackoverflow.com/questions/39946052/how-to-coroutine-ipython-a-callback

import sys
from IPython import __version__
from IPython import embed  # $site/IPython/terminal/embed.py
from IPython.terminal.ipapp import load_default_config

print "versions: IPython %s  python %s" % (
        __version__, sys.version.split()[0] )

def pdict( header, adict ):
    print header
    for k, v in sorted( adict.items() ):
        print "%s\t: %s" % (k, v)

config = load_default_config()
pdict( "load_default_config:", config )

aglobal = [3]

#...............................................................................
def callback( adict ):
    # pdict( "callback:", adict )
    t = adict["t"]
    x = 3
    embed( header="callback: t %d" % t )
        # interact: print t x ...
        # ^D / EOF
    return

def aloop( *args ):
    for t in range( 3 ):
        callback( locals() )

aloop( 1, 2, 3 )  # works in "run this.py"
# but typing "aloop()" in an IPython terminal -&gt;
# embed.py:218: UserWarning: Failed to get module unknown module
#  global_ns.get('__name__', 'unknown module')
</code></pre>

<p>You could insert a breakpoint, which would give similar outcome:</p>

<pre><code>import pdb; pdb.set_trace()
</code></pre>

<p><a href="https://docs.python.org/3.6/library/pdb.html" rel="nofollow">https://docs.python.org/3.6/library/pdb.html</a></p>

<p>Alternative here (<code>embed()</code> function within iPython):
<a href="http://stackoverflow.com/questions/16867347/step-by-step-debugging-with-ipython">Step-by-step debugging with IPython</a></p>

python scipy ipython coroutine