IPython的使用大全

作者: 何同尘 | 来源:发表于2019-01-14 23:21 被阅读15次

安装IPython

pip install ipython
ipython #启动

或者使用ipython notebook

jupyter notebook#启动

在IPython里查看帮助文档

简单的说,有三种方法
使用 help 函数可以查看函数描述
使用 ? 可以查看函数,对象等的描述和用法
使用 ?? 可以在的基础上追加源码,前提是该函数是由python语言编写的。
使用TAB可以对命令进行补全
如果并不知道首字符,只知道中间的匹配项,也可以使用*来做匹配.

In [1]: help(len)
In [2]: len?
In [3]: len??
In [4]: import h<TAB>
hashlib             hmac                http         
heapq               html                husl  
In [5]: *Warning?
BytesWarning                  RuntimeWarning
DeprecationWarning            SyntaxWarning
FutureWarning                 UnicodeWarning
ImportWarning                 UserWarning
PendingDeprecationWarning     Warning
ResourceWarning

在IPython的一些快捷键

Keystroke Action
Ctrl-a 光标回到行首
Ctrl-e 光标回到行末
Ctrl-b or the left arrow key 光标后移一位
Ctrl-f or the right arrow key 光标前移一位
------------------------------- --------------------------------------------------
Backspace key Delete previous character in line
Ctrl-d 删除光标后的字符
Ctrl-k 剪切光标后的字符
Ctrl-u 剪切光标前的字符
------------------------------- --------------------------------------------
Ctrl-l 清除屏幕
Ctrl-c 中止命令
Ctrl-d 退出ipython会话
------------------------------------- --------------------------------------------
Ctrl-p (or the up arrow key) 进入历史的上一个命令
Ctrl-n (or the down arrow key) 进入历史的下一个命令
Ctrl-r 搜索命令历史

魔术命令

代码粘贴命令

有时候想要在其他地方复制一段代码,可直接在命令行里粘贴会报错,就可以使用%paste%cpaste命令。
先在其他地方复制一段代码,然后

In [3]: %paste
>>> def donothing(x):
...     return x

## -- End pasted text --

PS:只需输入%paste
%cpaste在输完之后留了一个交互空间,可以像文本编辑器一样输入。

代码执行命令

%run可以用来执行外部py脚本,函数,代码。

#-------------------------------------
# file: myscript.py

def square(x):
    """square a number"""
    return x ** 2

for N in range(1, 4):
    print(N, "squared is", square(N))

你可以在IPython会话中执行:

In [6]: %run myscript.py
1 squared is 1
2 squared is 4
3 squared is 9

代码计时命令

%timeit
统计一行代码的执行时间

In [8]: %timeit L = [n ** 2 for n in range(1000)]
1000 loops, best of 3: 325 µs per loop
```也可以使用``%%timeit``统计代码块的执行时间。
```ipython
In [9]: %%timeit
   ...: L = []
   ...: for n in range(1000):
   ...:     L.append(n ** 2)
   ...: 
1000 loops, best of 3: 373 µs per loop

更多的魔术命令

%magic %lsmagic %timeit?

In [12]: %lsmagic
Available line magics:
%alias  %alias_magic  %autoawait  %autocall  %autoindent  %automagic  %bookmark  %cd  %cls  %colors  %config  %copy  %cpaste  %ddir  %debug  %dhist  %dirs  %doctest_mode  %echo  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %macro  %magic  %matplotlib  %mkdir  %notebook  %page  %paste  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %popd  %pprint  %precision  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %quickref  %recall  %rehashx  %reload_ext  %ren  %rep  %rerun  %reset  %reset_selective
  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext
%who  %who_ls  %whos  %xdel  %xmode

Available cell magics:
%%!  %%HTML  %%SVG  %%bash  %%capture  %%cmd  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%markdown  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile

Automagic is ON, % prefix IS NOT needed for line magics.

In Out 的妙用

在ipython中的每个会话都有编号,就是In ,如果有输出就有一个Out编号。在整个过程可以直接调用。

In [4]: print(In)
In [5]: Out
In [6]: Out[2] ** 2 + Out[3] ** 2
#也可以用_来代替上一个输出,__代表第上两个输出。
In [7]: print(_)
In [8]: print(__)
In [9]: print(___)
#也可以判断第4次输入是否有输出
In [10]: 14 in Out
#查看历史命令
In [16]: %history -n 1-4
   1: import math
   2: math.sin(2)
   3: math.cos(2)
   4: print(In)

在IPython中执行shell命令

所谓shell命令就是在系统中执行的命令。
ipython可以直接执行系统命令,这是普通python环境所没有的。

In [1]: !ls
myproject.txt

In [2]: !pwd
/home/jake/projects/myproject

In [3]: !echo "printing from the shell"
printing from the shell

也可以对命令的返回值赋值

In [4]: contents = !ls

In [5]: print(contents)
['myproject.txt']

In [6]: directory = !pwd

In [7]: print(directory)
['/Users/herui/notebooks/tmp/myproject']

也可以使用魔法命令代替

In [14]: %cd ..
/home/herui/projects
%cat %cp %env %ls %man %mkdir %more %rm %pwd等等

错误与调试

错误栈样式
使用魔法命令%xmode是exception mode的缩写。它有三种模式。plain,Context,Verbose,默认为Context.
修改模式:

%xmode Plain

调试:%debug 进入错误环境,然后可以自己调试。

Exception reporting mode: Plain
Automatic pdb calling has been turned ON

Traceback (most recent call last):

  File "<ipython-input-9-569a67d2d312>", line 3, in <module>
    func2(1)

  File "<ipython-input-1-d849e34d61fb>", line 7, in func2
    return func1(a, b)

  File "<ipython-input-1-d849e34d61fb>", line 2, in func1
    return a / b

ZeroDivisionError: division by zero



> <ipython-input-1-d849e34d61fb>(2)func1()
      1 def func1(a, b):
----> 2     return a / b
      3 
#在这里:
ipdb> print(b)
0
ipdb> quit

时间和效率记录

四个命令
%time
%timeit
%prun ==> program run
lprun ==> line program run
time 和 timeit 不再展示

def sum_of_lists(N):
    total = 0
    for i in range(5):
        L = [j ^ (j >> i) for j in range(N)]
        total += sum(L)
    return total

%prun sum_of_lists(1000000)
%lprun -f sum_of_lists sum_of_lists(5000)
结果像这样:
Timer unit: 1e-06 s

Total time: 0.009382 s
File: <ipython-input-19-fa2be176cc3e>
Function: sum_of_lists at line 1

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     1                                           def sum_of_lists(N):
     2         1            2      2.0      0.0      total = 0
     3         6            8      1.3      0.1      for i in range(5):
     4         5         9001   1800.2     95.9          L = [j ^ (j >> i) for j in range(N)]
     5         5          371     74.2      4.0          total += sum(L)
     6         1            0      0.0      0.0      return total

更多内容请查看官方文档!

相关文章

网友评论

    本文标题:IPython的使用大全

    本文链接:https://www.haomeiwen.com/subject/passdqtx.html