In [6]: *Warning?
BytesWarning
DeprecationWarning
FutureWarning
ImportWarning
PendingDeprecationWarning
ResourceWarning
RuntimeWarning
SyntaxWarning
UnicodeWarning
UserWarning
Warning
In [7]: str.*find*?
str.find
str.rfind
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2、IPython shell中的快捷键
2.1、导航快捷键
快捷键
动作
Ctrl-a
将光标移动到本行开始处
Ctrl-e
将光标移动到本行结尾处
Ctrl-b or ← 箭头
将光标回退一个字符
Ctrl-f or → 箭头
将光标前进一个字符
2.2、文本输入快捷键
快捷键
动作
Backspace 键
删除前一个字符
Ctrl-d
删除后一个字符
Ctrl-k
从光标开始剪切至行尾
Ctrl-u
从行头剪切至光标
Ctrl-y
Yank(即粘贴)之前剪切的文本
Ctrl-t
Transpose(即交换)前两个字符
2.3、命令历史快捷键
快捷键
动作
Ctrl-p or ↑ 箭头
获取前一个历史命令
Ctrl-n or ↓ 箭头
获取后一个历史命令
Ctrl-r
对历史命令的反向搜索
In [11]: def square(a):
...: """返回参数的平方"""
...: return a ** 2
...:
I-search backward: squ
1
2
3
4
5
6
7
2.4、其他快捷键
快捷键
动作
Ctrl-l
清空终端屏幕显示内容
Ctrl-c
中断当前的Python命令
Ctrl-d
退出IPython会话
3、IPython魔法命令
行魔法命令:以 % 开头,作用于单行输入
单元魔法命令:以 %% 开头,作用于多行输入
3.1、粘贴代码块:%paste 和 %cpaste
用来解决一些由复制粘贴带来的代码格式问题
%paste:粘贴并执行
%cpaste:科安提示粘贴并执行多个代码块
In [11]: def donothing(x):
...: return x
...:
In [12]: def donothing(x):
...: ...: return x
...:
In [13]: %paste
def donothing(x):
...: return x
## -- End pasted text --
1
2
3
4
5
6
7
8
9
10
11
12
13
3.2、执行外部代码:%run
用于执行外部python文件
执行后,可使用文件内部函数
可以使用 %run? 来查看帮助文档
3.3、计算代码运行时间:%timeit
会自动多次执行命令,以获取更稳定的结果
可用于分析某个步骤执行耗时
%timeit L =[n **2for n inrange(1000)]
1
206 µs ± 1.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
1
%%timeit
L =[]for n inrange(1000):
L.append(n **2)
1
2
3
4
237 µs ± 2.27 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
1
L =[]for n inrange(5):%timeit L.append(n **2)
1
2
3
218 ns ± 2.31 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
215 ns ± 1.84 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
211 ns ± 0.921 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
211 ns ± 1.45 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
213 ns ± 0.561 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
deffunc1(a, b):return a/b
deffunc2(x):
a = x
b = x -1return func1(a, b)
1
2
3
4
5
6
7
func2(1)
1
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-2-7cb498ea7ed1> in <module>
----> 1 func2(1)
<ipython-input-1-1643401e3e36> in func2(x)
5 a = x
6 b = x - 1
----> 7 return func1(a, b)
<ipython-input-1-1643401e3e36> in func1(a, b)
1 def func1(a, b):
----> 2 return a/b
3
4 def func2(x):
5 a = x
ZeroDivisionError: division by zero
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
%xmode Plain
1
Exception reporting mode: Plain
1
func2(1)
1
Traceback (most recent call last):
File "<ipython-input-5-7cb498ea7ed1>", line 1, in <module>
func2(1)
File "<ipython-input-1-1643401e3e36>", line 7, in func2
return func1(a, b)
File "<ipython-input-1-1643401e3e36>", line 2, in func1
return a/b
ZeroDivisionError: division by zero
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
%xmode Verbose
1
Exception reporting mode: Verbose
1
func2(1)
1
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-7-7cb498ea7ed1> in <module>
----> 1 func2(1)
global func2 = <function func2 at 0x111187950>
<ipython-input-1-1643401e3e36> in func2(x=1)
5 a = x
6 b = x - 1
----> 7 return func1(a, b)
global func1 = <function func1 at 0x111187680>
a = 1
b = 0
<ipython-input-1-1643401e3e36> in func1(a=1, b=0)
1 def func1(a, b):
----> 2 return a/b
a = 1
b = 0
3
4 def func2(x):
5 a = x
ZeroDivisionError: division by zero
Exception reporting mode: Plain
Automatic pdb calling has been turned ON
Traceback (most recent call last):
File "<ipython-input-2-f80f6b5cecf3>", line 3, in <module>
func2(1)
File "<ipython-input-1-1643401e3e36>", line 7, in func2
return func1(a, b)
File "<ipython-input-1-1643401e3e36>", line 2, in func1
return a/b
ZeroDivisionError: division by zero
> [0;32m<ipython-input-1-1643401e3e36>[0m(2)[0;36mfunc1[0;34m()[0m
[0;32m 1 [0;31m[0;32mdef[0m [0mfunc1[0m[0;34m([0m[0ma[0m[0;34m,[0m [0mb[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m
[0m[0;32m----> 2 [0;31m [0;32mreturn[0m [0ma[0m[0;34m/[0m[0mb[0m[0;34m[0m[0;34m[0m[0m
[0m[0;32m 3 [0;31m[0;34m[0m[0m
[0m[0;32m 4 [0;31m[0;32mdef[0m [0mfunc2[0m[0;34m([0m[0mx[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m
[0m[0;32m 5 [0;31m [0ma[0m [0;34m=[0m [0mx[0m[0;34m[0m[0;34m[0m[0m
[0m
ipdb> print(b)
0
ipdb> quit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
命令
描述
list
显示文件的当前路径
h(elp)
显示命令列表,或查询特定命令的帮助信息
q(uit)
退出调试器和程序
c(ontinue)
退出调试器,继续运行程序
n(ext)
调到程序下一步
<enter>
重复前一个命令
p(rint)
打印变量
s(tep)
步入子程序
r(eturn)
从子程序跳出
7、代码的分析和计时
%time:对单个语句的执行时间计时
%timeit:对单个语句的重复执行进行计时,以获取更高的精准度
%prun:利用分析器运行代码
%lprun:利用逐行分析器运行代码
%memit:测量单个语句的内存使用
%mprun:通过逐行的内存分析器运行代码
7.1、代码段计时:%timeit 和 %time
%timeit 通常比 %time 运行快
%timeit sum(range(100))
1
752 ns ± 3.06 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
1
%%timeit
total =0for i inrange(1000):for j inrange(1000):
total += i *(-1)** j
1
2
3
4
5
267 ms ± 3.86 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
1
import random
L =[random.random()for i inrange(100000)]%timeit L.sort()
1
2
3
447 µs ± 29.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
1
import random
L =[random.random()for i inrange(100000)]print("无序序列排序好耗时")%time L.sort()
1
2
3
4
无序序列排序好耗时
CPU times: user 14.7 ms, sys: 340 µs, total: 15.1 ms
Wall time: 15.3 ms
1
2
3
print("有序序列排序好耗时")%time L.sort()
1
2
有序序列排序好耗时
CPU times: user 1.04 ms, sys: 0 ns, total: 1.04 ms
Wall time: 1.04 ms
1
2
3
%%time
total =0for i inrange(1000):for j inrange(1000):
total += i *(-1)** j
1
2
3
4
5
CPU times: user 310 ms, sys: 3.11 ms, total: 314 ms
Wall time: 314 ms
1
2
7.2、分析整个脚本:%prun
defsum_of_lists(N):
total =0for i inrange(5):
L =[j^(j >> i)for j inrange(N)]
total +=sum(L)return total
1
2
3
4
5
6
%prun sum_of_lists(1000000)
1
7.3、用 %lprun 进行逐行分析
需要安装:pip install line_profiler
IPython 导入 line_profiler:%load_ext line_profiler
%load_ext line_profiler
1
%lprun -f sum_of_lists sum_of_lists(5000)
1
7.4、用 %memit 和 %mprun 进行内存分析
安装:pip install memory_profiler
引用:%load_ext memory_profiler
%mprun:该函数仅仅对独立模块内部的函数有效
%load_ext memory_profiler
1
from mprun_demp import sum_of_lists
1
%memit sum_of_lists(1000000)
1
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-2-104416b8696e> in <module>
----> 1 get_ipython().run_line_magic('memit', 'sum_of_lists(1000000)')
~/opt/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
2312 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2313 with self.builtin_trap:
-> 2314 result = fn(*args, **kwargs)
2315 return result
2316
<~/opt/anaconda3/lib/python3.7/site-packages/decorator.py:decorator-gen-127> in memit(self, line, cell)
~/opt/anaconda3/lib/python3.7/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
185 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
--> 187 call = lambda f, *a, **k: f(*a, **k)
188
189 if callable(arg):
~/opt/anaconda3/lib/python3.7/site-packages/memory_profiler.py in memit(self, line, cell)
1052 timeout=timeout, interval=interval,
1053 max_usage=True,
-> 1054 include_children=include_children)
1055 mem_usage.append(tmp)
1056
~/opt/anaconda3/lib/python3.7/site-packages/memory_profiler.py in memory_usage(proc, interval, timeout, timestamps, include_children, multiprocess, max_usage, retval, stream, backend, max_iterations)
341 # Therefore, the whole process hangs indefinitely. Here, we are ensuring that the process gets killed!
342 try:
--> 343 returned = f(*args, **kw)
344 parent_conn.send(0) # finish timing
345 ret = parent_conn.recv()
~/opt/anaconda3/lib/python3.7/site-packages/memory_profiler.py in _func_exec(stmt, ns)
825 # helper for magic_memit, just a function proxy for the exec
826 # statement
--> 827 exec(stmt, ns)
828
829
<string> in <module>
NameError: name 'sum_of_lists' is not defined