IPython A Comprehensive Guide to Launch and Use it
IPython A Comprehensive Guide to Launch and Use it

What is IPython : A Comprehensive Guide to Launch and Use it

GET FREE AMZAON AUDIOBOOKS

Although there are many tools today that can work as development environments in Python, there are some specific tools that have a useful interactive interface. IPython is one of them. Think like that, if you consider python as the engine of the data science task then IPython is the interactive control Panel. In this entire comprehensive guide, you will learn how to use the full functionality of Ipython.

What is IPython

IPython is an interactive shell built with Python. It provides a large number of useful syntactic additions to the python language. Many New beginners can think of it as a programming language but it is not. It is just a Python interpreter with extra features. Following are the major features of it.

  1. It has powerful python shells (Terminal and QT Console).
  2. Web-Based Notebook that is popularly known as Jupyter Notebook
  3. It supports interactive data visualizations.
  4. It is easy to use and provides high performance on Parallel Computing.

How to install IPython

If you have not installed IPython in your system. Then you can install it using the pip (For python)  and conda (For Anaconda) command. Installing using pip requires checking the python version. If you have installed Python 2.xx version then go for pip and for  Python 3.xx version, go for pip3. However, for anaconda, it is not the case.

Python 2.xx 

pip install ipython

Python 3.xx 

pip3 install ipython

Anaconda

conda update conda
conda update ipython

Using the same method you can install it on any OS like Ubuntu, Linux, Mac e.t.c.

IPython Shell vs Notebook: Which one to use?

After the installation of IPython, there are two ways you can use it. First is the IPython shell and IPython Notebook. The first one is like a command prompt and the latter is a browser-based notebook. However, syntax and functionality are the same.

How to launch IPython Shell

IPyhon shell can be launch by typing the IPython in your terminal or command prompt.

ipython
Starting IPython Shell
Starting IPython Shell

How to launch IPython Notebook

Jupyter Notebook is the browser-based GUI of the IPython shell. To launch the web-based notebook, type the Jupyter notebook on the terminal.

jupyter notebook
Starting Jupyter Notebook
Starting Jupyter Notebook

The command will launch a local webserver with a specific port. Your default browser will automatically open on this address. If it is not then you can copy the URL address and open it in your browser.

Help and Documentation in IPython

For a programmer, the best practice in coding is not to memorize everything. While coding in python there are certain things that come to mind of programmers. These are

  1. How to call this function? And what are its arguments?
  2. What will be the source code of the object?
  3. What are the modules in a package I am importing? And its objects and method.

Although if you can find answers to all these questions on internet forums like StackOverflow, online documentation. But you can find the answers to it in IPython using ‘? ‘,  ‘??‘  characters, and tab key.  Let’s learn all of these in the upcoming sections.

Access Documentation with ?

Python language is specifically built by knowing the user or coder’s mind. Every method, function are well documented by reference to the string, known as the docstring. It is called a summary of any object and how you can use it. In python, you can access it using the built-in help() method. For example, I want to see the documentation of the len function then  I will execute the following code.

help(len)

Output

Accessing Documentation using help method
Accessing Documentation using the help method

The output will depend upon your interpreter. You can get output inline or in the window.

Look how the len() method is well documented. Due to the popular use of help() method to get the object information. IPython comes with a ‘?‘ character. Use it as the suffix for any method or object it will output the information.

len?

Output

Accessing Documentation using single what character
Accessing Documentation using single what character

This notation also works on any object method. For example, I am creating a list and want to see what does the insert method does. Execute the lines of code in your ipython shell.

L = [10,20,30,40]
L.insert?

Output

Accessing Object Method Documentation
Accessing Object Method Documentation

Even you can use the “?” on your object also like L?

L?
Accessing Object Documentation
Accessing Object Documentation

You can also define your own function and put your documentation there. To do so you have to write your function summary in the string literal (“””, “””). After that, you can access documentation using ? character. Look at the image below.

Accessing Custom Method Documentation
Accessing Custom Method Documentation

 

In the figure, you can see I am creating an addition add() function that takes two parameters a and b. Inside the method, there is a docstring.” You can see the method docs using ‘?’ as a suffix of the function name.

add?

Know to Access Source Code with ??

With a single what(?) character, you can get documentation on the object definitions, parameters e.t.c. But using the double what character(??), you can know the source code of any custom-defined object and function. You cannot access the source code for the built-in object and method.

Using the same example (add function), If I use the ?? after the add function name, then IPython will show the source code of it.

add??
Accessing Custom Method Source Code using double What character
Accessing Custom Method Source Code using double What character

If you will use the same on the built-in function like len?? then you will not get the source code but it will display the output the same as len?

Double what on the len method
Double what on the len method

So using the ? and ?? can give you quick insights into the object you want to use in your code. In the next section, you will explore tab completion.

Modules Exploration using Tab in IPython

The other feature of IPython is the use of automatic tab completion. You can explore all the details of the object and its method easily.

Object Contents using the tab

Tab explorer allows you to know which method you can use with the associate object. For example, I have created a list L and want to know all the methods I can use on it. Then I will first type L.<TAB>(press tab keyboard after .). It will list out all the methods of the object.

Object Contents using the tab
Object Contents using the tab

You can also get the list of method starting with some characters using L.in<TAB>.

Some Object Contents using the tab
Some Object Contents using the tab

Tab Completion on Importing

Just like you have used tab completion for getting the list of the object method. You can also know all the objects in a package using the tab completion after the import.

from time import <TAB>
Tab Completion on import
Tab Completion on import

If you use some character and then use the tab completion after the import then you will see only the list of objects starting with that character.

from time import t<TAB>
Tab Completion on import using some character matching
Tab Completion on import using some character matching

If you directly use the tab completion after the import, then it will list out all the packages installed in your system.

import <TAB>
Tab completion on only import statement
Tab completion on the only import statement

You can see in the above figure the tab completion has listed out all the packages installed in my system.

Shortcuts in IPython Shell

Shortcuts are very useful while typing. IPython has keyboard shortcuts that allow you to navigate fast while typing the commands. These shortcuts may differ depending on your system. Below is the various category of shortcuts that you can use.

Navigation Shortcuts

You can use the left, right arrow keys for moving left and right. But using the given shortcuts you can quickly navigate.

  1. Ctrl +a:  Move the cursor to the beginning of the line.
  2. Ctrl+e: Move the cursor to the end of the line.
  3. Ctrl + b(or left arrow key) : Move back one character.
  4. Ctrl+f(or right arrow key) : Move forward one character.

Text Entry/ Deletion Shortcuts

I know you can use the backspace key to delete a character. But IPython allows you to delete a character, word, and entire lines of text using shortcuts. Below is it.

  1. Ctrl+d: Delete the next character in the line.
  2. Ctrl+k:  Allows to Cut text from the cursor to the end of the line.
  3. Ctrl + u:  Cut text from beginning to line of cursor.
  4. Ctrl + y:  Paste text that was previously cut.
  5. Ctrl+t:  Transpose or switch the previous two characters.

Command History Shortcuts

IPython also allows you to use the command that was used in recent times. All the used commands are stored in the SQLite database in your IPython profile directory.  The easied way to access it is using the up and down key. But there are some other shortcuts also and some of them are below.

Ctrl + p (or up key): Access previous command in history.

Ctrl +n(or down key): It allows you to access the next command in history.

Other Useful Shortcuts

All the above shortcuts are mostly used for accessing and editing. The shortcuts that I will describe here are for manipulating the terminal.

Ctrl+I: Clear terminal screen.

Ctrl +c: Interrupt the current python command.

Ctrl + d: Exist the current IPython session.

These shortcuts might look tedious at first, but slowly they will be automatic after you practice them.

IPython Magic Command

IPython has some addon on top of normal python syntax. And these are known as magic commands. There are two types of magic command. One is line magic and the other is cell magic commands. The first one is denoted by a single percentage sign(%) and the latter as a double percentage sign(%%). Both are used as prefixes. Let’s learn the uses of it.

%paste

Suppose you have lines of code that you have copied from somewhere. Most of the cases when you directly paste to your shell or notebook. You will get an unexpected indent error. That’s why %paste comes as a savior. Just copy the code from anywhere and type the %paste command. It will paste as well as execute the code.

%run

While working on larger projects, You may require some store or external python source code to reuse. IPython allows you to run the existing source code using the %run command. For example, I have stored add_numbers.py and I want to reuse then I will use the following command.

The python file contains the following code.

def add_numbers(a,b):
    return a+b

print(add_numbers(5,10))
%run add_numbers.py

The output will be 15

Run existing Python file using run magic command
Run existing Python file using run magic command

%timeit

Sometimes you have two versions of solving the problem. Now you want to check the execution time for both of them. The %time allows you to find execution time for a single line of code. But to find execution time for multiple lines of code you have to use %%timit. Run the following command.

%timeit L = [n ** 2 for n in range(10000)]

Output

Using timeit magic command on list comphrension
Using timeit magic command on list comphrension
%%timeit
...: L = []
...: for n in range(1000):
...: L.append(n ** 2)
...:

Output

Using timeit for multiple lines of code
Using timeit for multiple lines of code

You can clearly see the latter for loop is taking more time than the list comprehension method. This way using timeit you can choose the method you want to use.

It’s best practice not to memorize everything that the commands do. Just like there is documentation of every method and object in python. IPython has also docstrings for magic commands.

You can use ? as the prefix on any command to know the details on it.  For example, I want to know about timeit then I will use %timeit?

timeit docstring
timeit docstring

And if you want to know all the list of magic command available, just type %lsmagic

%lsmagic

Output

List of magic commands
List of magic commands

Run shell commands in IPython

In IPython you can run all the shell commands within the terminal. All these are possible with the exclamation point(%). Anything after the% the sign will not be executed by the python interpreter but by the system command line.

If you have already an understanding of how to run a command on the Unix system. Then IPython will run most of the commands and some commands may fail. But that’s ok as most generic commands will run in the IPython shell.

Shell Commands in IPython

You can use shell commands in IPython using the! character as the prefix. For example, I want to know all the files and directories in the current path then I will use %ls.

%ls
ls Shell command in IPython
ls Shell command in IPython

In the same, I can run %pwd , %echo “Welcome to the data science learner website”.

%pwd

Output

Path of current directory
Path of the current directory
%echo "Welcome to the data science learner website"

Output

Echo command in Ipython shell
Echo command in Ipython shell

Passing Values to and from the Shell

IPythpn allows you to pass the results from the command. Then after you can use it as the Python variable. For example contents of the current working path will be assigned to the contents of the variables. And if I print it then you will see the output as a list(not exactly of this type).

contents = %ls
print(contents)

In the same way, you can pass the python variables to the shell and execute it. Execute the lines of code.

message = "How are you?"
%echo {message}
Using python variable with shell command
Using python variable with shell command

Please note that not all the shell or Linux commands can be used with the % prefix. There are some other commands that can be only be executed when you will use it with % as the prefix. For example %cat , %cd, %env, %man,%mkdir, e.t.c. If the automagic is on for your IPython shell then you can use all of them without % character.

 

Conclusion

This tutorial is a depth guide to know how IPython can make python coding very easy and efficient. Here you have learned to access documentation of the objects and source code of the custom methods or function. You knew the various shortcuts that you can manipulate the IPython without clicking mouse buttons.   How to store shell command output and use to and from in python.  If you are a beginner and want to learn python then start with an IPython shell or notebook. This article was for them. If you have any other queries on IPython then you can contact us for more help.

 

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner