What is IPython ?

  • IPython is an python interpreter shell built on top standard interpreter.
  • Lot of handy features.
  • 12+ years of development.
  • IPython notebook was started recently and gained huge attention.
  • IPython is mostly used in scientific community.

Show off

In [1]:
# Tab completion

l = []
In [2]:
l.append(2)
In [3]:
# Better help system. obj?
l?
In [4]:
# Read the source code of function

def square(no):
    """Square a given number"""
    return no * no
In [5]:
square? # same as help(square)
In [6]:
square??
In [7]:
# Let's display all inbuiltin function in python, starting with s.
# How can we do it ?
# Regex !!!

s*?
In [8]:
# Ipython stores all the input and Output in dictionaries.
# Lets see what was the input for cell 4.

In[4]
Out[8]:
u'# Read the source code of function\n\ndef square(no):\n    """Square a given number"""\n    return no * no'
In [10]:
Out[4] # Expect KeyError, since Input didn't produce an output.
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-10-dc56a5919233> in <module>()
----> 1 Out[4] # Expect KeyError, since Input didn't produce an output.

KeyError: 4
In [12]:
a = 23; a+23
Out[12]:
46
In [13]:
In[12]
Out[13]:
u'a = 23; a+23'
In [19]:
Out[12]
Out[19]:
46
In [20]:
# _ -> Previous cell output
# __ -> previous to previous cell output
print _, __
46 a = 23; a+23

In [21]:
# *nix has history command, in similar way IPython also has a way to display inputs

%history -n 1-5
   1:
# Tab completion

l = []
   2: l.append(2)
   3:
# Better help system. obj?
l?
   4:
# Read the source code of function

def square(no):
    """Square a given number"""
    return no * no
   5: square?

In [23]:
# From IPython it is possible to run linux command
# For command with arguments syntax is `%ls -la`
!ls
5d329791bf724833a4d9cfee9835b63a_w75_h76.jpeg
Blaze
Developer-Indian-Cities-Ananlysis
Ezhil-Lang
NoPriv
SlideshareAPIExamples
Song-Fetcher
Untitled0.ipynb
Why to use IPython.ipynb
appfolio
bangalore.python.org.in
baseframe
blog
bootstrap.min.css
brubeck
cheese1
coaster
color-theme-6.6.0
color-theme-6.6.0.tar.gz
cookiecutter-flask-kracekumar
cppcheck
crate.web
crawlit
crawlit.ipynb
crawlit_queue.json
detail?name=mod_wsgi-3.4.tar.gz
digfont
django-pdf
django-todo
djcode
download.mp4?lecture_id=10
dropbox-maildir
dukaan
emacs-env
emacs-for-python
email
empythoned
envs
eve
factor
falcon
fb_conv.txt
flask-babelex
flask-commentease
flask-lastuser
flow
funnel
github.com
go-instagram
go-maildir
go-photo-organizer
golang-slides
gunicorn
hackerrank
hacknight
hasanalysis
hasgeek-vagrant
hasgeek.tv
hasgeek_vagrant
hasjob
hasjob_8_8_2013.sql
hasmail
hasweb
homebrew
http
httpbin
httpie
imgee
indian_mobile_number
ipython-in-depth
kracekumar.com

lastuser
lastuser_8_8_2013.sql
lecture_slides%2Fsection1%2F2_pl_intro.pdf
lecture_slides%2Fsection1%2F3_ML_expressions_and_variable_bindings.pdf
libev
logs
mail_backup_local.db
mail_backup_local.log
maildir
markdown-converter
matplotlib
md
mongrel2
nodular
nodular-test
nodules
offline-python
peopleflow
phonecat
playstore
presentation
presentz_https
proglang-002
proglang-002%2Flecture_slides%2Fsection0%2F2b_grading_policy.pdf
promises-demo
py-photo-organiser-read-only
pycon-feedback-1.html
pycon-feedback-1.pdf
pycon-feedback-1.rst
pyres
python-intro
python-training
python_koans
reddit-comment-fetcher
reveal.js
rq-dashboard
rust-mode.el
schematics
snippets
tango_with_django
tango_with_django_project
tease.py
test-empythoned
test.pdf
testcookiecutter
todo
tumblr
uncompyle2
usergrid
veewee-raring64
wtforms

In [24]:
pwd
Out[24]:
u'/Users/kracekumar/code'
In [25]:
# IPython also allows to store output of a command
files = !ls /
In [26]:
print(files)
['Applications', 'Library', 'Network', 'System', 'Users', 'Volumes', 'bin', 'cores', 'dev', 'etc', 'home', 'mach_kernel', 'net', 'opt', 'private', 'sbin', 'tmp', 'usr', 'var']

In [27]:
!echo $files
[Applications, Library, Network, System, Users, Volumes, bin, cores, dev, etc, home, mach_kernel, net, opt, private, sbin, tmp, usr, var]

In [35]:
# In Python any method starting with __ is called magic method. Similarly in IPython %%command is magic function.
%timeit [] + [] # only one line is possible
10000000 loops, best of 3: 126 ns per loop

In [36]:
%%timeit x = range(100000) #multiline is possible
x.append(23)
10000000 loops, best of 3: 114 ns per loop

In [37]:
%%bash
echo "My shell is:" $SHELL
My shell is: /bin/zsh

In [38]:
%%ruby
puts "Guido and Matz use Emacs."
Guido and Matz uses Emacs.

In [41]:
%lsmagic
Out[41]:
Available line magics:
%alias  %alias_magic  %autocall  %automagic  %autosave  %bookmark  %cd  %clear  %colors  %config  %connect_info  %debug  %dhist  %dirs  %doctest_mode  %ed  %edit  %env  %gui  %hist  %history  %install_default_config  %install_ext  %install_profiles  %killbgscripts  %less  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %lsmagic  %macro  %magic  %man  %matplotlib  %more  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %popd  %pprint  %precision  %profile  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %rep  %rerun  %reset  %reset_selective  %run  %save  %sc  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode

Available cell magics:
%%!  %%HTML  %%SVG  %%bash  %%capture  %%debug  %%file  %%html  %%javascript  %%latex  %%perl  %%prun  %%pypy  %%python  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile

Automagic is ON, % prefix IS NOT needed for line magics.
In [42]:
%%writefile hello.py

# -*- coding: utf-8 -*-

def greet(name):
    return "Hello {}".format(name)

if __name__ == "__main__":
    print(greet("Pythonistas!"))
Writing hello.py

In [43]:
!cat hello.py

# -*- coding: utf-8 -*-

def greet(name):
    return "Hello {}".format(name)

if __name__ == "__main__":
    print(greet("Pythonistas!"))
In [44]:
%run hello.py
Hello Pythonistas!

In [46]:
!python hello.py
Hello Pythonistas!

In [47]:
# We all know cell can take Markdown or code snippet. The output is displayed in browser. So IPython notebook can display Images
# videos, embed, plot graphs etc ...
# Lets show off

from IPython.display import Image, YouTubeVideo
YouTubeVideo("d1a4Jbjc-vU")
Out[47]:
In [48]:
Image("/Users/kracekumar/code/imgee/imgee/static/uploads/1b562ef1a0174658ad67dbf19ee5c45e_w75_h76.jpeg")
Out[48]:
In [50]:
Image("http://imgs.xkcd.com/comics/python.png")
Out[50]:
In [51]:
from IPython.display import HTML
s = """
<table>
    <tr>
        <td> Name </td>
        <td> Twitter </td>
    </tr>
    <tr>
        <td> Kracekumar </td>
        <td> @kracetheking </td>
    </tr>
    <tr>
        <td> James Dennis </td>
        <td> @j2labs </td>
    </tr>
</table>"""
HTML(s)
Out[51]:
Name Twitter
Kracekumar @kracetheking
James Dennis @j2labs
In [52]:
# How about embeding IFrame ? Soundcloud ?
HTML("""<iframe width="100%" height="166" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/114267245&amp;color=ff6600&amp;auto_play=false&amp;show_artwork=true"></iframe>""")
Out[52]:
In [65]:
# Future ?
# Lot more features

Thanks

Twitter: kracetheking

In [ ]: