IPython的使用大全

安装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

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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,907评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,987评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,298评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,586评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,633评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,488评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,275评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,176评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,619评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,819评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,932评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,655评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,265评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,871评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,994评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,095评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,884评论 2 354

推荐阅读更多精彩内容