Python Basics #5 — IPython

4 min read

In today’s lesson we’ll cover the IPython shell.

When you’re learning Python or writing code, you’ll often use the Python shell to test snippets quickly. The Python shell is an application that runs the Python interpreter in interactive mode — much like the Windows command prompt or the Terminal on macOS / Linux. If you’ve used a JavaScript console in a browser, the idea is similar.

If you installed Anaconda Python, IPython is already included. If you’re on a regular CPython install, you can install it with:

pip install ipython

If you’d rather install Anaconda Python, see Python Basics #2 — Installing Python.

Let’s compare the standard Python shell with IPython.

First, the standard shell. Run the command python in your terminal (Windows command prompt, or macOS / Linux terminal). The Python version prints, followed by the shell prompt >>>.

Print “Hello World”:

>>> print('Hello World!')
Hello World!

Define a variable and print its value:

>>> myvar = 'This is myvar variable'
>>> print(myvar)
This is myvar variable

Import the os module and print the current working directory:

>>> import os
>>> os.getcwd()
'C:\\\\Users\\\\Curtis'

Now let’s try a for loop.

>>> for i in range(10):
...   print(i)
...
0
1
2
3
4
5
6
7
8
9

The Python shell lets you run small snippets without saving a source file.

Now let’s see how IPython differs from the standard shell. Type ipython in your terminal to start it. Let’s run the same code we just tried:

In [1]: print('Hello World!')
Hello World!

Unlike the standard shell, IPython provides syntax highlighting for better readability.

It also offers tab completion, which the standard shell doesn’t:

In [2]: myvar = 'This is myvar variable'
In [3]: print(myvar)
This is myvar variable

You can also list every function inside a module:

In [4]: import os
In [5]: os.getcwd()
Out[5]: 'D:\\\\OneDrive\\\\Projects\\\\Python Tutorials\\\\tutorial 5'

Use ? to get docs on a module, function, or method:

In [6]: os?
Type:        module
String form: <module 'os' from 'C:\\\\Users\\\\CURTIS\\\\anaconda3\\\\lib\\\\os.py'>
File:        c:\\users\\curtis\\anaconda3\\lib\\os.py
Docstring:
OS routines for NT or Posix depending on what system we're on.

This exports:
- all functions from posix or nt, e.g. unlink, stat, etc.
- os.path is either posixpath or ntpath
- os.name is either 'posix' or 'nt'
- os.curdir is a string representing the current directory (always '.')
- os.pardir is a string representing the parent directory (always '..')
- os.sep is the (or a most common) pathname separator ('/' or '\\\\')
- os.extsep is the extension separator (always '.')
- os.altsep is the alternate pathname separator (None or '/')
- os.pathsep is the component separator used in $PATH etc
- os.linesep is the line separator in text files ('\\r' or '\\n' or '\\r\\n')
- os.defpath is the default search path for executables
- os.devnull is the file path of the null device ('/dev/null', etc.)

Programs that import and use 'os' stand a better chance of being
portable between different platforms.  Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join).

In [7]: os.getcwd?
Signature: os.getcwd()
Docstring: Return a unicode string representing the current working directory.
Type:      builtin_function_or_method

Finally, IPython provides magic functions that handle things you’d otherwise need to import a module for. Let’s quickly see a few. List files in the current directory; create a test folder and cd into it; and so on. There are many more — print the full list with the command below.

In [18]: %quickref

IPython -- An enhanced Interactive Python - Quick Reference Card
================================================================

obj?, obj??      : Get help, or more help for object (also works as
?obj, ??obj).
?foo.*abc*       : List names in 'foo' containing 'abc' in them.
%magic           : Information about IPython's 'magic' % functions.

Magic functions are prefixed by % or %%, and typically take their arguments
without parentheses, quotes or even commas for convenience.  Line magics take a
single % and cell magics are prefixed with two %%.

Example magic function calls:

%alias d ls -F   : 'd' is now an alias for 'ls -F'
alias d ls -F    : Works if 'alias' not a python name
alist = %alias   : Get list of aliases to 'alist'
cd /usr/share    : Obvious. cd -<tab> to choose from visited dirs.
%cd??            : See help AND source for magic %cd
%timeit x=10     : time the 'x=10' statement with high precision.
%%timeit x=2**100
x**100           : time 'x**100' with a setup of 'x=2**100'; setup code is not
counted.  This is an example of a cell magic.

System commands:

!cp a.txt b/     : System command escape, calls os.system()
cp a.txt b/      : after %rehashx, most system commands work without !
---Return to continue, q to quit---

As mentioned, the Python shell is a handy tool for testing code snippets and modules during development, and for quick experimentation while learning. Get comfortable with it.

That wraps up this lesson. Next time we’ll cover Jupyter Notebook.

X