Python - ipHelp.py

From Torben's Wiki
Jump to navigationJump to search


Attention: today this is easier:

pip install ipython
...
from IPython import embed  
...
embed()  # to drop into iPython Shell from within the code

Carsten Knoll wrote a nice module that improves the display of execeptions and allows to open an ipython shell at a certain point of the program code: See [1]

# ipHelp.py
# by Carsten Knoll
import sys
import new
__version__ = "0.2"
try:
    from IPython.Shell import IPShellEmbed
    args = ['-pi1','In <\\#>: ','-pi2','   .\\D.: ',
                '-po','Out<\\#>: ','-nosep']
    class AdaptedIPSE(IPShellEmbed):
        def __init__(self, *args, **kwargs):

            IPShellEmbed.__init__(self, *args, **kwargs)
            old_interact = self.IP.interact # save the real method
            def new_interact(self, *args):
                self.IP.user_ns.update({'_ips_exit':False})
                old_interact(*args) # call the real interact method
                if self.IP.user_ns['_ips_exit']:
                    def do_nothing(*args, **kwargs):
                        pass
                    self.IP.interact = do_nothing
            self.IP.interact = new.instancemethod(new_interact, self,
                                                                  type(self))
    IPS= AdaptedIPSE(args,
                           banner = 'Dropping into IPython',
                           exit_msg = 'Leaving Interpreter, back to program.')
    def ip_syshook(pdb=0, mode=2):
        import IPython.ultraTB
        modus = ['Plain', 'Context', 'Verbose'][mode] # select the mode
        sys.excepthook = IPython.ultraTB.FormattedTB(mode=modus,
                                        color_scheme='Linux', call_pdb=pdb)

    def ip_extra_syshook(fnc, pdb=0, filename=None):
        assert callable(fnc)
        import IPython.ultraTB
        import time
        if not filename == None:
            assert isinstance(filename, str)
            pdb = 0
        ip_excepthook = IPython.ultraTB.FormattedTB(mode='Verbose',
                                        color_scheme='Linux', call_pdb=pdb)
        fileTraceback = IPython.ultraTB.FormattedTB(mode='Verbose',
                                        color_scheme='NoColor', call_pdb=0)
        def theexecphook (type, value, traceback):
            fnc()
            ip_excepthook(type, value, traceback)
            # write this to a File without Colors
            if not filename == None:
                outFile = open(filename, "a")
                outFile.write("--" + time.ctime()+" --\n")
                outFile.write(fileTraceback.text(type, value, traceback))
                outFile.write("\n-- --\n")
                outFile.close()
        sys.excepthook = theexecphook
    from IPython.Debugger import Tracer
    ST=Tracer()
except ImportError:
    # create dummy functions
    def IPS():
        print "(EE): IPython is not available"
        pass
    def ip_syshook(*args):
        pass

    def ST():
        pass

Now include this file in your project and place IPS() somewhere in your code to open a shell there.

from ipHelp import IPS, ip_syshook
ip_syshook() # (1) -> debugger on exception
# run IPS() somewhere to open ipython shell

If you have are unsing PyQT and you get the message "QCoreApplication::exec: The event loop is already running", inserting the following into your __init__ of your main class will help:

QtCore.pyqtRemoveInputHook()