#!/usr/bin/env python # coding: utf-8 # # A few things that work best/only at the IPython terminal or Qt console clients # ## Running code with `%run` # In[1]: get_ipython().run_cell_magic('writefile', 'script.py', "x = 10\ny = 20\nz = x+y\nprint('z is: %s' % z)\n") # In[2]: get_ipython().run_line_magic('run', 'script') # In[3]: x # ## Event loop and GUI integration # The `%gui` magic enables the integration of GUI event loops with the interactive execution loop, allowing you to run GUI code without blocking IPython. # # Consider for example the execution of Qt-based code. Once we enable the Qt gui support: # In[4]: get_ipython().run_line_magic('gui', 'qt') # We can define a simple Qt application class (simplified version from [this Qt tutorial](http://zetcode.com/tutorials/pyqt4/firstprograms)): # In[5]: import sys from PyQt4 import QtGui, QtCore class SimpleWindow(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setGeometry(300, 300, 200, 80) self.setWindowTitle('Hello World') quit = QtGui.QPushButton('Close', self) quit.setGeometry(10, 10, 60, 35) self.connect(quit, QtCore.SIGNAL('clicked()'), self, QtCore.SLOT('close()')) # And now we can instantiate it: # In[6]: app = QtCore.QCoreApplication.instance() if app is None: app = QtGui.QApplication([]) sw = SimpleWindow() sw.show() from IPython.lib.guisupport import start_event_loop_qt4 start_event_loop_qt4(app) # But IPython still remains responsive: # In[7]: 10+2 # The `%gui` magic can be similarly used to control Wx, Tk, glut and pyglet applications, [as can be seen in our examples](https://github.com/ipython/ipython/tree/master/examples/lib). # ## Embedding IPython in a terminal application # In[8]: get_ipython().run_cell_magic('writefile', 'simple-embed.py', "# This shows how to use the new top-level embed function. It is a simpler\n# API that manages the creation of the embedded shell.\n\nfrom IPython import embed\n\na = 10\nb = 20\n\nembed(header='First time', banner1='')\n\nc = 30\nd = 40\n\nembed(header='The second time')\n") # The example in kernel-embedding shows how to embed a full kernel into an application and how to connect to this kernel from an external process. # ## Logging terminal sessions and transitioning to a notebook # The `%logstart` magic lets you log a terminal session with various degrees of control, and the `%notebook` one will convert an interactive console session into a notebook with all input cells already created for you (but no output).