#!/usr/bin/env python # coding: utf-8 # # IPython: an enviromnent for interactive computing # ## What is IPython? # # - Short for *I*nteractive *Python* # - A platform for you to *interact* with your code and data # - The *notebook*: a system for *literate computing* # * The combination of narrative, code and results # * Weave your scientific narratives together with your computational process # - Tools for easy parallel computing # * Interact with *many* processes # # IPython at the terminal # The basic IPython client: at the terminal, simply type `ipython`: # # $ ipython # Python 3.4.3 (default, Feb 24 2015, 22:44:40) # Type "copyright", "credits" or "license" for more information. # # IPython 3.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??' for extra details. # # In [1]: print("hello world") # hello world # # In the **notebook** use the `help` menu, then `about`: # # Server Information: # # You are using Jupyter notebook. # # The version of the notebook server is 5.0.0.dev-21a6aec and is running on: # Python 3.5.2 |Anaconda custom (x86_64)| (default, Jul 2 2016, 17:52:12) # [GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] # # Current Kernel Information: # # Python 3.5.2 |Anaconda custom (x86_64)| (default, Jul 2 2016, 17:52:12) # Type "copyright", "credits" or "license" for more information. # # IPython 5.2.0.dev -- 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??' for extra details. # # Some other tutorial help/resources : # # - The [Jupyter website](http://jupyter.org) # - Search for "IPython in depth" tutorial on youtube and pyvideo, much longer, much deeper # - Ask for help on [Stackoverflow, tag it "ipython"](http://stackoverflow.com/questions/tagged/ipython) or "Jupyter" # - [Mailing list](http://mail.scipy.org/mailman/listinfo/ipython-dev) # - File a [github issue](http://github.com/jupyter/help) # - [Twitter](https://twitter.com/projectjupyter) # - [Reddit](http://www.reddit.com/r/IPython) # - [Notebook Gallery](https://github.com/ipython/ipython/wiki/A-gallery-of-interesting-IPython-Notebooks) # - full books # - Come talk to the team! We're In BIDS ! # # IPython: beyond plain Python # When executing code in IPython, all valid Python syntax works as-is, but IPython provides a number of features designed to make the interactive experience more fluid and efficient. # ## First things first: running code, getting help # In the notebook, to run a cell of code, hit `Shift-Enter`. This executes the cell and puts the cursor in the next cell below, or makes a new one if you are at the end. Alternately, you can use: # # - `Alt-Enter` to force the creation of a new cell unconditionally (useful when inserting new content in the middle of an existing notebook). # - `Control-Enter` executes the cell and keeps the cursor in the same cell, useful for quick experimentation of snippets that you don't need to keep permanently. # In[1]: print("Hello") # # ## Getting help # In[2]: get_ipython().show_usage() # ## Help with `?` and `??` # # Typing `object_name?` will print all sorts of details about any object, including docstrings, function definition lines (for call arguments) and constructor details for classes. # In[3]: import collections get_ipython().run_line_magic('pinfo', 'collections.namedtuple') # In[4]: get_ipython().run_line_magic('pinfo2', 'collections.Counter') # In[5]: get_ipython().run_line_magic('psearch', '*int*') # An IPython quick reference card: # In[6]: get_ipython().run_line_magic('quickref', '') # ## Tab completion # Tab completion, especially for attributes, is a convenient way to explore the structure of any object you’re dealing with. Simply type `object_name.` to view the object’s attributes. Besides Python objects and keywords, tab completion also works on file and directory names. # In[7]: collections. # # In[8]: collections.namedtuple( # # ## The interactive workflow: input, output, history # In[9]: 2 + 10 # In[10]: _ + 10 # # ## Output control # # You can suppress the storage and rendering of output if you append `;` to the last cell (this comes in handy when plotting with matplotlib, for example): # In[11]: 10+20; # In[12]: _ # ## Output history # # The output is stored in `_N` and `Out[N]` variables: # In[13]: #This number (11) may be change, depending on the execution number of the cell above. _11 == Out[11] # In[14]: Out # And the last three have shorthands for convenience: # In[15]: print('last output:', _) print('next one :', __) print('and next :', ___) # ### Output vs Display # In[16]: 1+1 # In[17]: print(1+1) # Can you spot the difference in the 2 above cells ? # ## The input history is also available # In[18]: In[11] # In[19]: _i # In[20]: _ii # In[21]: print('last input:', _i) print('next one :', _ii) print('and next :', _iii) # In[22]: get_ipython().run_line_magic('history', '') # # # Accessing the underlying operating system # # **Note:** the commands below work on Linux or Macs, but may behave differently on Windows, as the underlying OS is different. IPython's ability to access the OS is still the same, it's just the syntax that varies per OS. # In[23]: #For Windows users, change to !dir get_ipython().system('pwd') # In[24]: files = get_ipython().getoutput('ls') print("My current directory's files:") print(files) # In[25]: get_ipython().system('echo $files') # In[26]: get_ipython().system('echo {files[0].upper()}') # ## Beyond Python: magic functions # The IPyhton 'magic' functions are a set of commands, invoked by prepending one or two `%` signs to their name, that live in a namespace separate from your normal Python variables and provide a more command-like interface. They take flags with `--` and arguments without quotes, parentheses or commas. The motivation behind this system is two-fold: # # - To provide an orthogonal namespace for controlling IPython itself and exposing other system-oriented functionality. # # - To expose a calling mode that requires minimal verbosity and typing while working interactively. Thus the inspiration taken from the classic Unix shell style for commands. # In[27]: get_ipython().run_line_magic('magic', '') # Line vs cell magics: # In[28]: get_ipython().run_line_magic('timeit', 'range(10)') # In[29]: get_ipython().run_cell_magic('timeit', '', 'range(10)\nrange(100)\n') # Line magics can be used even inside code blocks: # In[30]: import sys results = [] for i in range(5): size = i*10 print('size:',size) result = get_ipython().run_line_magic('timeit', '-o list(range(size))') results.append(result) results # Magics can do anything they want with their input, so it doesn't have to be valid Python: # In[31]: get_ipython().run_cell_magic('bash', '', 'echo "My shell is:" $SHELL\necho "My memory status is:" free\n') # Another interesting cell magic: create any file you want locally from the notebook: # In[32]: get_ipython().run_cell_magic('writefile', 'test.txt', 'This is a test file!\nIt can contain anything I want...\n\nmore...\n') # In[33]: get_ipython().system('cat test.txt') # Let's see what other magics are currently defined in the system: # In[34]: get_ipython().run_line_magic('lsmagic', '') # ## Running normal Python code: execution and errors # Not only can you input normal Python code, you can even paste straight from a Python or IPython shell session: # In[35]: # Fibonacci series: # the sum of two elements defines the next a, b = 0, 1 while b < 10: print(b) a, b = b, a+b # In[36]: for i in range(10): print(i), # ## Error display # And when your code produces errors, you can control how they are displayed with the `%xmode` magic: # In[37]: get_ipython().run_cell_magic('writefile', 'mod.py', '\ndef f(x):\n return 1.0/(x-1)\n\ndef g(y):\n return f(y+1)\n') # Now let's call the function `g` with an argument that would produce an error: # In[38]: import mod mod.g(0) # ## Plain exceptions # In[39]: get_ipython().run_line_magic('xmode', 'plain') mod.g(0) # ## Verbose exceptions # In[40]: get_ipython().run_line_magic('xmode', 'verbose') mod.g(0) # The default `%xmode` is "context", which shows additional context but not all local variables. Let's restore that one for the rest of our session. # In[41]: get_ipython().run_line_magic('xmode', 'context') # ## Raw Input in the notebook # Jupyter notebook web application support `raw_input`(python2), or `input` (python3) which for example allow us to invoke the `%debug` magic in the notebook: # In[42]: mod.g(0) # In[43]: get_ipython().run_line_magic('debug', '') # Don't foget to exit your debugging session. Raw input can of course be use to ask for user input: # In[44]: enjoy = input('Are you enjoying this tutorial ?') print('enjoy is :', enjoy) # ## Plotting in the notebook # This imports numpy as `np` and matplotlib's plotting routines as `plt`, plus setting lots of other stuff for you to work interactivel very easily: # In[45]: get_ipython().run_line_magic('matplotlib', 'inline') # In[46]: import numpy as np import matplotlib.pyplot as plt # Let's look at the results we collected earlier: # In[48]: results[0].all_runs # In[49]: [1]*3 # In[50]: fig, ax = plt.subplots() for i,r in enumerate(results): ax.scatter([i+1]*len(r.all_runs),r.all_runs) ax.set_title("An exponetial") # In[51]: x = np.linspace(0, 2*np.pi, 300) y = (1-np.exp(-x*0.5)) ax.set_ylim(0,1) ax.set_xlim(0,6) ax.plot(x, y) ax.set_xlabel('More loops (Units)') ax.set_ylabel('Measurements (s)') # In[52]: fig # # The IPython kernel/client model # In[53]: get_ipython().run_line_magic('connect_info', '') # # That's all folks! #