IPython – Installation

IPython – Installation ”; Previous Next IPython is included by default in Anaconda distribution of Python. It can be downloaded from Anaconda’s download page www.anaconda.com/download/ Binaries for all major OS (Windows, MacOS and Linux) and architecture (32 bit and 64 bit) are available on this link. To install IPython separately in standard Python installation, you can use pip command as shown below − pip3 install ipython IPython internally uses following packages − Sr.No. IPython dependencies & Functionality 1 colorama Cross-platform API for printing colored terminal text from Python 2 jedi An autocompletion tool for Python 3 pickleshare Small ‘shelve’ like datastore with concurrency support 4 prompt_toolkit Library for building powerful interactive command lines in Python 5 pygments Syntax highlighting package written in Python 6 simplegeneric Simple generic functions 7 traitlets Configuration system for Python applications. In general, all dependencies get installed automatically. Else, you can install them individually using pip. Print Page Previous Next Advertisements ”;

IPython – Getting Started

IPython – Getting Started ”; Previous Next This chapter will explain how to get started with working on IPython. Starting IPython from Command Prompt. Before proceeding to understand about IPython in depth, note that instead of the regular >>>, you will notice two major Python prompts as explained below − In[1] appears before any input expression. Out[1] appears before the Output appears. Besides, the numbers in the square brackets are incremented automatically. Observe the following screenshot for a better understanding − Now, if you have installed Anaconda distribution of Python, open Anaconda prompt from start menu. Start IPython from conda prompt When compared to regular Python console, we can notice a difference. The IPython shell shows syntax highlighting by using different colour scheme for different elements like expression, function, variable etc. Another useful enhancement is tab completion. We know that each object has one or more methods available as defined in its class. IPython pops up appropriate list of methods as you press tab key after dot in front of object. In the following example, a string is defined. As a response, the methods of string class are shown. IPython provides information of any object by putting ‘?’ in front of it. It includes docstring, function definitions and constructor details of class. For example to explore the string object var defined above, in the input prompt enter var?. The result will show all information about it. Observe the screenshot given below for a better understanding − Magic Functions IPython’s in-built magic functions are extremely powerful. There are two types of magic functions. Line magics, which work very much like DOS commands. Cell magics, which work on multiple lines of code. We shall learn about line magic functions and cell magic functions in detail in subsequent chapters. Print Page Previous Next Advertisements ”;

IPython – History Command

IPython – History Command ”; Previous Next IPython preserves both the commands and their results of the current session. We can scroll through the previous commands by pressing the up and down keys. Besides, last three objects of output are stored in special variables _, __ and ___. The history magic command shows previous commands in current session as shown in the screenshot given below − Print Page Previous Next Advertisements ”;

IPython – System Commands

IPython – System Commands ”; Previous Next If the statement in the input cell starts with the exclamation symbol (!), it is treated as a system command for underlying operating system. For example, !ls (for linux) and !dir (for windows) displays the contents of current directory The output of system command can also be assigned to a Python variable as shown below − The variable stores output without colors and splits at newline characters. It is also possible to combine Python variables or expressions with system command calls. Variable in curly brackets {} can be embedded in command text. Observe the following example − Here is another example to understand that prefixing Python variable with $ also achieves the same result. Print Page Previous Next Advertisements ”;

Setting IPython as Default Python Environment

Setting IPython as Default Python Environment ”; Previous Next Different environment variables influence Python’s behaviour. PYTHONSTARTUP environment variable is assigned to a Python script. As an effect, this script gets executed before Python prompt appears. This is useful if certain modules are to be loaded by default every time a new Python session starts. The following script (start.py) imports IPython module and executes start_ipython() function to replace default Python shell with prompt (>>>) by IPython shell when Python executable is invoked. import os, IPython os.environ[”PYTHONSTARTUP”] = ”” IPython.start_ipython() raise SystemExit Assuming that this file is stored in Python’s installation directory (c:python36), set PYTHONSTARTUP environment variable and start Python from command line. Then IPython shell appears as shown below − Note that the environment variable can be permanently set using System Properties dialog in Windows and using export command on Linux. Print Page Previous Next Advertisements ”;

IPython – Command Line Options

IPython – Command Line Options ”; Previous Next In this chapter, let us understand how to work with various command line options in IPython. Invoking IPython Program You can invoke an IPython program using the following options − C:python36> ipython [subcommand] [options] [-c cmd | -m mod | file] [–] [arg] The file option is a Python script with .py extension. If no other option is given, the script is executed and command prompt reappears. C:python36>ipython hello.py Hello IPython welcome to interactive computing Subcommands and Parameters An IPython command accepts the following subcommand options − Profile − Create and manage IPython profiles. Kernel − Start a kernel without an attached frontend. Locate − Print the path to the IPython dir. History − Manage the IPython history database. An IPython profile subcommand accepts the following parameters − ipython profile create myprofile − Creates a new profile. ipython profile list − Lists all available profiles. ipython locate profile myprofile − Locates required profile. To install new IPython kernel, use the following command − Ipython kernel –install –name To print the path to the IPython dir, use the following command − C:python36>ipython locate myprofile C:Usersacer.ipython Besides, we know that − The history subcommand manages IPython history database. The trim option reduces the IPython history database to the last 1000 entries. The clear option deletes all entries. Some of the other important command line options of IPython are listed below − Sr.No. IPython Command & Description 1 –automagic Turn on the auto calling of magic commands. 2 –pdb Enable auto calling the pdb debugger after every exception. 3 –pylab Pre-load matplotlib and numpy for interactive use with the default matplotlib backend. 4 –matplotlib Configure matplotlib for interactive use with the default matplotlib backend. 5 –gui=options Enable GUI event loop integration with any of (”glut”, ”gtk”, ”gtk2”,”gtk3”, ”osx”, ”pyglet”, ”qt”, ”qt4”, ”qt5”, ”tk”, ”wx”, ”gtk2”, ”qt4”). The sample usage of some of the IPython command line options are shown in following table − Sr.No. IPython Command & Description 1 ipython –matplotlib enable matplotlib integration 2 ipython –matplotlib=qt enable matplotlib integration with qt4 backend 3 ipython –profile=myprofile start with profile foo 4 ipython profile create myprofile create profile foo w/ default config files 5 ipython help profile show the help for the profile subcmd 6 ipython locate print the path to the IPython directory 7 ipython locate profile myprofile print the path to the directory for profile `myprofile` Print Page Previous Next Advertisements ”;

Dynamic Object Introspection

IPython – Dynamic Object Introspection ”; Previous Next IPython has different ways of obtaining information about Python objects dynamically. In this chapter, let us learn the ways of dynamic object introspection in IPython. Use of ? and ?? provides specific and more detailed information about the object. In the first example discussed below, a simple integer object a is created. Its information can be procured by typing a ? in the input cell. In the second example, let us define a function and introspect this function object with ? and ??. Note that the magic function %psearch is equivalent to the use of ? or ?? for fetching object information. Print Page Previous Next Advertisements ”;

Running & Editing Python Script

IPython – Running and Editing Python Script ”; Previous Next In this chapter, let us understand how to run and edit a Python script. Run Command You can use run command in the input prompt to run a Python script. The run command is actually line magic command and should actually be written as %run. However, the %automagic mode is always on by default, so you can omit this. In [1]: run hello.py Hello IPython Edit Command IPython also provides edit magic command. It invokes default editor of the operating system. You can open it through Windows Notepad editor and the script can be edited. Once you close it after saving its input, the output of modified script will be displayed. In [2]: edit hello.py Editing… done. Executing edited code… Hello IPython welcome to interactive computing Note that hello.py initially contained only one statement and after editing one more statement was added. If no file name is given to edit command, a temporary file is created. Observe the following code that shows the same. In [7]: edit IPython will make a temporary file named: C:UsersacerAppDataLocalTempipython_edit_4aa4vx8fipython_edit_t7i6s_er.py Editing… done. Executing edited code… magic of IPython Out[7]: ”print (“magic of IPython”)” Print Page Previous Next Advertisements ”;

IPython – Magic Commands

IPython – Magic Commands ”; Previous Next Magic commands or magic functions are one of the important enhancements that IPython offers compared to the standard Python shell. These magic commands are intended to solve common problems in data analysis using Python. In fact, they control the behaviour of IPython itself. Magic commands act as convenient functions where Python syntax is not the most natural one. They are useful to embed invalid python syntax in their work flow. Types of Magic Commands There are two types of magic commands − Line magics Cell magics Line Magics They are similar to command line calls. They start with % character. Rest of the line is its argument passed without parentheses or quotes. Line magics can be used as expression and their return value can be assigned to variable. Cell Magics They have %% character prefix. Unlike line magic functions, they can operate on multiple lines below their call. They can in fact make arbitrary modifications to the input they receive, which need not even be a valid Python code at all. They receive the whole block as a single string. To know more about magic functions, the built-in magics and their docstrings, use the magic command. Information of a specific magic function is obtained by %magicfunction? Command. Let us now describe some of the built-in line and cell magic commands. Built-in line magics %autocall [mode] This magic function makes a function automatically callable without having to use parentheses. It takes three possible mode parameters: 0 (off), 1 (smart) is default or 2 (always on). %automagic Magic functions are callable without having to type the initial % if set to 1. Without arguments it toggles on/off. To deactivate, set to 0. The following example shows a magic function %pwd (displays present working directory) being called without leading % when %automagic set to 1 %cd This line magic changes the current directory. This command automatically maintains an internal list of directories you visit during your IPython session, in the variable _dh. You can also do ‘cd -<tab>’ to see directory history conveniently. Usage The %cd command can be used in the following ways − %cd <dir> − Changes current working directory to <dir> %cd.. − Changes current directory to parent directory %cd − changes to last visited directory. %dhist This magic command prints all directories you have visited in current session. Every time %cd command is used, this list is updated in _dh variable. %edit This magic command calls upon the default text editor of current operating system (Notepad for Windows) for editing a Python script. The script is executed as the editor is closed. %env This magic command will list all environment variables. It also reads value of particular variable or set the value of environment variable. Usage The %cd command can be used in the following ways − %env − Lists all environment variables %env var − Gets value for var %env var val − Sets value for var %gui [GUINAME] When used without argument this command enables or disables IPython GUI event loop integration. With GUINAME argument, this magic replaces the default GUI toolkits by the specified one. Sr.No. Command & Description 1 %gui wx enable wxPython event loop integration 2 %gui qt4|qt enable PyQt4 event loop integration 3 %gui qt5 enable PyQt5 event loop integration 4 %gui gtk enable PyGTK event loop integration 5 %gui gtk3 enable Gtk3 event loop integration 6 %gui tk enable Tk event loop integration 7 %gui osx enable Cocoa event loop integration 8 (requires %matplotlib 1.1) 9 %gui disable all event loop integration %lsmagic Displays all magic functions currently available %matplotlib This function activates matplotlib interactive support during an IPython session. However, it does not import matplotlib library. The matplotlib default GUI toolkit is TkAgg. But you can explicitly request a different GUI backend. You can see a list of the available backends as shown − In [4]: %matplotlib –list Available matplotlib backends: [”osx”, ”qt4”, ”qt5”, ”gtk3”, ”notebook”, ”wx”, ”qt”, ”nbagg”,”gtk”, ”tk”, ”inline”] The IPython session shown here plots a sine wave using qt toolkit − While using Jupyter notebook, %matplotlib inline directive displays plot output in the browser only. %notebook This function converts current IPython history into an IPython notebook file with ipynb extension. The input cells in previous example are saved as sine.ipynb %notebook sine.ipynb %pinfo This function is similar to object introspection ? character. To obtain information about an object, use the following command − %pinfo object This is synonymous to object? or ?object. %precision This magic function restricts a floating point result to specified digits after decimal. %pwd This magic function returns the present working directory. %pylab This function populates current IPython session with matplotlib, and numpy libraries. %recall When executed without any parameter, this function executes previous command. Note that in %recall n, number in front of it is input cell number. Hence the command in the nth cell is recalled. You can recall commands in section of cells by using command such as %recall 1-4. Current input cell is populated with recalled cell and the cursor blinks till the enter key is pressed. %run This command runs a Python script from within IPython shell. %time This command displays time required by IPython environment to execute a Python expression. %timeit This function also displays time required by IPython environment to execute a Python expression. Time execution of a Python statement or expression uses the timeit module. This function can be used both as a line and cell magic as explained here − In line mode you can time a single-line. In cell mode, the statement in the first line is used as setup code and the body of the cell is timed. The cell body has access to any variables created in the setup code. %who This line magic prints all interactive variables, with some minimal formatting. If any arguments are given, only variables whose type matches one of these are printed. IPython Custom Line Magic function

IPython – Introduction

IPython – Introduction ”; Previous Next Project Jupyter is a suite of software products used in interactive computing. IPython was originally developed by Fernando Perez in 2001 as an enhanced Python interpreter. A web based interface to IPython terminal in the form of IPython notebook was introduced in 2011. In 2014, Project Jupyter started as a spin-off project from IPython. Packages under Jupyter project include − Jupyter notebook − A web based interface to programming environments of Python, Julia, R and many others QtConsole − Qt based terminal for Jupyter kernels similar to IPython nbviewer − Facility to share Jupyter notebooks JupyterLab − Modern web based integrated interface for all products. Standard distribution of Python comes with a REPL (Read-Evaluate-Print Loop) environment in the form of Python shell with >>> prompt. IPython (stands for Interactive Python) is an enhanced interactive environment for Python with many functionalities compared to the standard Python shell. Features of IPython IPython offers more features compared to the standard Python. They are as follows − Offers a powerful interactive Python shell. Acts as a main kernel for Jupyter notebook and other front end tools of Project Jupyter. Possesses object introspection ability. Introspection is the ability to check properties of an object during runtime. Syntax highlighting. Stores the history of interactions. Tab completion of keywords, variables and function names. Magic command system useful for controlling Python environment and performing OS tasks. Ability to be embedded in other Python programs. Provides access to Python debugger. History and Development IPython was originally developed by Fernando Perez in 2001. Its current version is IPython7.0.1 which requires Python 3.4 version or higher. IPython 6.0 was the first version to support Python 3. Users having Python 2.7 should work with IPython’s version 2.0 to 5.7 The concept of computational notebooks started in 80s decade when MATLAB and Mathematica were released. These GUI frontends to the interactive shell had features like text formatting, adding graphics, table and adding mathematical symbols. Sage notebook is also a web based notebook. Creaters of IPython started working on notebook interface for IPython shell in 2005. IPython notebook soon added support of other languages like R and Julia. It was in 2014, that Perez started Jupyter project as a spin-off project from IPython, since IPython project was becoming big with products like notebook server and Qt console added to it. Since IPython 4.0, all additional components were shifted to Project Jupyter and adding support of other languages to IPython notebook. IPython continues to focus on improvement of its enhanced interpreter feature. It also provides primary kernel to Jupyter notebook frontend. Print Page Previous Next Advertisements ”;