Skip to content Skip to sidebar Skip to footer

How To Coroutine Ipython <-> A Callback()

In an IPython terminal, I want a function deep in main() to go back to IPython, where I can print, set ... as usual, then keep running main(): IPython run main.py ... d

Solution 1:

You could insert a breakpoint, which would give similar outcome:

import pdb; pdb.set_trace()

https://docs.python.org/3.6/library/pdb.html

Alternative here (embed() function within iPython): Step-by-step debugging with IPython

Solution 2:

Adapting the answer in https://stackoverflow.com/a/24827245/901925, I added an Ipython embed (https://ipython.org/ipython-doc/3/api/generated/IPython.terminal.embed.html)

import numpy as np
from scipy.optimize import minimize, rosen
import time
import warnings
from IPython import embed

classTookTooLong(Warning):
    passclassMinimizeStopper(object):
    def__init__(self, max_sec=60):
        self.max_sec = max_sec
        self.start = time.time()
    def__call__(self, xk=None):
        elapsed = time.time() - self.start
        if elapsed > self.max_sec:
            embed(header='FirstTime')
            warnings.warn("Terminating optimization: time limit reached",
                          TookTooLong)
        else:
            # you might want to report other stuff hereprint("Elapsed: %.3f sec" % elapsed)

# example usage
x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
res = minimize(rosen, x0, method='Nelder-Mead', callback=MinimizeStopper(1E-3))

with a run like:

1251:~/mypy$ python3 stack39946052.py 
Elapsed: 0.001 sec
Python 3.5.2 (default, Jul  52016, 12:43:10) 
Type "copyright", "credits" or "license"formoreinformation.

IPython 5.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use'object??' forextra details.


FirstTime

In [1]: xk
Out[1]: array([ 1.339,  0.721,  0.824,  1.71 ,  1.236])

In [2]: elapsed
Out[2]: 0.0010917186737060547

In [3]: self.max_sec
Out[3]: 0.001

In [4]: self.max_sec=1000

In [5]:                                                                                         
Do you really want to exit ([y]/n)? y

stack39946052.py:20: TookTooLong: Terminating optimization: time limit reached
  TookTooLong)
....

Post a Comment for "How To Coroutine Ipython <-> A Callback()"