📜 ⬆️ ⬇️

IPython advanced usage

This tool is familiar to most Python developers.
At the same time, not many people are suspicious about the extensive capabilities provided by this interactive shell, using mostly auto-completion.

Terminal 2014 python 2014 125 ճ 0image

The article is based on excerpts from the extensive, understandable and beautiful documentation ipython.github.com/ipython-doc/dev/interactive/index.html
Let's skip over such obvious things as autocompletion and command history, saved by calls.

')

Object Overview


In [1]: import datetime
In [2]: datetime?
Type: module
Base Class: <type 'module'>
String Form: <module 'datetime' from '/usr/local/Cellar/python/2.7.1/lib/python2.7/lib-dynload/datetime.so'>
Namespace: Interactive
File: /usr/local/Cellar/python/2.7.1/lib/python2.7/lib-dynload/datetime.so
Docstring:
Fast implementation of the datetime type.


As you can see, we get enough detailed information about the object, which can be useful when debugging. There are also special commands % pdoc , % pdef , % psource and % pfile , which will help us see the documentation, the definition of the function, the source code and the full code of the file, respectively.

An example of the output of the % pdef command for json.dumps:

In [8]: %pdef json.dumps
json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, **kw)


Run command


Using this command, we are able to execute any python script and access all its data directly in the space of the interactive shell.

This is extremely useful when we are developing a module and want to be able to test and manipulate its data in a convenient way.

There is a set of keys that allow you to measure the execution time (-t), run with a debugger (-d) or profiler (-p).

If you need to refresh the memory of the magic commands provided by IPython, you can always use the hint ( % run? ).

Output caching


When using IPython, each input and output has a label.

In [11]: a = 9
In [12]: a
Out[12]: 9


This is encouraging, since we can handle the output without having to assign it to a specific variable. To do this, we use the syntax _number_label, or simply _, __ and ___, to refer to the last 3 conclusions:

In [13]: _
Out[13]: 9
In [14]: _ + 8
Out[14]: 17
In [15]: _
Out[15]: 17
In [16]: _13
Out[16]: 9


Output suppression


Sometimes the output of commands can be very large, which slows down the work and litters the console with unnecessary information.

In [21]: "*"*100500;
In [22]:


Putting a semicolon at the end of the expression, we report our categorical reluctance to see the output of the results.

Input history


There are 2 commands that allow you to view and manipulate the history of the entered lines: % hist and % rep

In [22]: %hist
1 : import datetime
2 : import json
3: a = 9
4: a
In [23]: %rep 1
In [24]: import datetime <- .


Calling system commands without exiting the shell


Using commands ! and !! , you can execute system shell commands, such as ls, cd, and others. The difference between the teams is that the first one simply executes the system command, the second one in addition allows to get and use the output of these commands.

In [26]: !ls
Archive Development Downloads Library Music Pictures VirtualBox VMs
Desktop Documents Dropbox Movies My Projects

In [27]: !!ls
Out[27]: SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):
0: Archive
1: Desktop
2: Development
3: Documents
4: Downloads
5: Dropbox
6: Library
7: Movies
8: Music
9: My
10: Pictures
11: Projects
12: VirtualBox VMs


Multiline editing


IPython can recognize expressions that require multiple lines, so there are no special problems with this, but there is room to grow. The % edit command will make your life better and will allow you not to avoid the definitions of functions and classes directly in the interactive shell.

Entering the % edit IPython command will open a system editor for us, where we will be able to edit our code in the usual way.

In [28]: %edit
IPython will make a temporary file named: /var/folders/9Q/9Q8AwQvdEUubQ84MwFcKt++++TI/-Tmp-/ipython_edit_YPjrQx.py
Editing... done. Executing edited code...
Out[28]: 'def amicool():\n\treturn True\n'
In [29]: amicool()
Out[29]: True
In [30]:


It is possible to open the editor with the previously entered code, for this is the command % edit -p
To refer to previously edited pieces of code, we can use the syntax % edit_output , in our case this is equivalent to % edit_28 .

View created IDs


I'll just leave it here:

In [32]: %who
a amicool datetime json

In [33]: %whos
Variable Type Data/Info
--------------------------------
a int 9
amicool function <function amicool at 0x1014f2848>
datetime module <module 'datetime' from '<...>lib-dynload/datetime.so'>
json module <module 'json' from '/usr<...>on2.7/json/__init__.pyc'>

In [34]:


Measurement of code execution time


Using the simple command % time and % timeit, we have the ability to measure the performance of individual pieces of code:

In [45]: %timeit [1,2,3,4,5][2]
1000000 loops, best of 3: 236 ns per loop

In [46]: %timeit (1,2,3,4,5)[2]
10000000 loops, best of 3: 34.3 ns per loop

In [54]: %time [1,2,3,4,5][2]
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s
Out[55]: 3




Once again, I recall a link to the documentation, ipython.github.com/ipython-doc/dev/interactive/index.html , where there are many interesting features not covered in this meager article. image

Source: https://habr.com/ru/post/117608/


All Articles