一、简介
2001年,Fernando Perez为了得到一个更为高效的交互式Python解释器而启动的一个项目,IPython不仅仅是一个加强版的shell,他可以直接进行绘图操作的GUI控制台,一个基于web的交互式笔记本,以及一个轻量级的快速并行计算引擎。
ipython
是一个升级版的交互式python命令行工具.
二、ipython安装
一、在已有Python环境安装
pip install ipython
等到命令执行完成后显示 successfully 表示完装成功,如下图
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsISPrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdsATOfd3bkFGazxCMx8VesATMfhHLlN3XnxCMwEzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5SMjFWY3U2N5MWOxYDO1YmZlRWMmVDNhFjNmVGMhR2Ni9CX5IzLcdDMxIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjL4M3Lc9CX6MHc0RHaiojIsJye.png)
安装完,在命令提示符下输入
ipython
就可以启动ipython了
其与原版python命令行工具不同在于ipython的提示符变成了in和out.
in
为输入命令的地方,
out
为命令执行完成后输出的地方
三、ipython常用操作
一、tab键自动补全一些常用的方法
1、常用命令
1 启动:ipython/ipython qtconsole –pylab=inline
2 Tab键自动补全
二、系统命令
1、支持一些系统命令
In [2]: pwd # 显示当前所在目录
Out[2]: '/root'
In [3]: cd .. # 返回当前目录的上一级目录
/
2、执行系统命令(!)
In [6]: !ifconfig
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.81.10 netmask 255.255.255.0 broadcast 192.168.81.255
inet6 fe80::a545:8b99:d507:4d0f prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:95:d5:31 txqueuelen 1000 (Ethernet)
RX packets 12851 bytes 9887304 (9.4 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 7172 bytes 1546188 (1.4 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1 (Local Loopback)
RX packets 140 bytes 12132 (11.8 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 140 bytes 12132 (11.8 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
In [7]: !ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 00:0c:29:95:d5:31 brd ff:ff:ff:ff:ff:ff
inet 192.168.81.10/24 brd 192.168.81.255 scope global ens33
valid_lft forever preferred_lft forever
inet6 fe80::a545:8b99:d507:4d0f/64 scope link
valid_lft forever preferred_lft forever
In [8]: !cat /etc/sysconfig/selinux
三、内省(?)
在变量名或命令的前面或后面加一个 “?” 并执行,可以用于显示该对象的一些通用信息,如对象类型、文档字符串等,这就叫做对象内省。这种操作查看到的信息,尤其是函数和类的信息,比通常直接引用变量名然后回车所看到的(repr)要好。“?” 的另一个用法是可以搜索 IPython 的命名空间,配合通配符使用效果如下:
In [1]:import numpy as np
In [2]:np.load?
np.load
np.loads
np.loadtxt
np.pkgload
使用双问号“??”还可以查看对象的源代码(如果可见的话)。
四、常用快捷键
1 Ctrl-P 或上箭头键 后向搜索命令历史中以当前输入的文本开头的命令
2 Ctrl-N 或下箭头键 前向搜索命令历史中以当前输入的文本开头的命令
3 Ctrl-R 按行读取的反向历史搜索(部分匹配)
4 Ctrl-Shift-v 从剪贴板粘贴文本
5 Ctrl-C 中止当前正在执行的代码
6 Ctrl-A 将光标移动到行首
7 Ctrl-E 将光标移动到行尾
8 Ctrl-K 删除从光标开始至行尾的文本
9 Ctrl-U 清除当前行的所有文本译注12
10 Ctrl-F 将光标向前移动一个字符
11 Ctrl-b 将光标向后移动一个字符
12 Ctrl-L 清屏
五、魔术命令
在 IPython 的会话环境中,所有文件都可以通过 %run 命令来当做脚本执行,并且文件中的变量也会随即导入当前命名空间。即,对于一个模块文件,你对他使用 %run 命令的效果和 from module import * 相同,除非这个模块文件定义了 main 函数(if name == ‘main:’),这种情况下 main 函数还会被执行。
这种以 % 开头的命令在 IPython 中被称为魔术命令,用于加强 shell 的功能。常用的魔术命令有:
1 %quickref 显示ipython的快速参考
2 %magic 显示所有的魔术命令的详细文档
3 %debug 从最新的异常跟踪的底部进入交互式调试器
4 %hist 打印命令的输入(可选输出)历史
5 %pdb 在异常发生后自动进入调试器
6 %paste 执行剪贴板中的python代码
7 %cpaste 打开一个特殊提示符以便手工粘贴待执行的python代码
8 %reset 删除interactive命名空间中的全部变量/名称
9 %page OBJECT 通过分页器打印输出object
10 %run script.py 在ipython中执行一个python脚本文件
11 %prun statement 通过cprofile执行statement,并打印分析器的输出结果
12 %time statement 报告statement的执行时间
13 %timeit statement 多次执行statement以计算系统平均执行时间.对那么执行时间非常小的代码很有用
14 %who,%who_id,%whos 显示interactive命名空间中定义的变量,信息级别/冗余度可变
15 %xdel variable 删除variable,并尝试清除其在ipython中的对象上的一切引用
对魔术命令不熟悉的话可以通过 %magic 查看详细文档;对某一个命令不熟悉的话,可以通过 %cmd? 内省机制查看特定文档。值得一提的是,IPython 中使用 del 命令无法删除所有的变量引用,因此垃圾回收机制也无法启用,所以有些时候你会需要使用 %xdel 或者 %reset。
1、测试代码的执行时间:
%time和%timeit
2、目录书签系统( 对目录做别名)
In [55]: %bookmark local /usr/local # 定义local书签
In [56]: %bookmark selinux /etc/sysconfig/selinux # 定义selinux书签
In [57]: %bookmark -l # 显示所有的书签
Current bookmarks:
local -> /usr/local
selinux -> /etc/sysconfig/selinux
In [55]: %bookmark local /usr/local
In [56]: %bookmark sysconfig /etc/sysconfig
In [57]: %bookmark -l
Current bookmarks:
local -> /usr/local
sysconfig -> /etc/sysconfig
In [58]: pwd
Out[58]: '/'
In [59]: cd local
(bookmark:local) -> /usr/local
/usr/local
In [60]: pwd
Out[60]: '/usr/local'
In [61]: cd sysconfig
(bookmark:sysconfig) -> /etc/sysconfig
/etc/sysconfig
In [62]: pwd
Out[62]: '/etc/sysconfig'
3、记录历史输入和输出
IPython能够记录整个控制台会话,包括输入和输出。执行%logstart即可开始记录日志。IPython的日志功能可以在任何时刻开启,它将记录你的整个会话(包括此前的命令)。此外还可以看看几个与之配套的魔术命令%logoff,%logon,%logstate以及%logstop。
4、与操作系统交互(IPython魔术命令)
命令 | 说明 |
---|---|
!cmd | 在系统shell中执行cmd |
output=!cmd args | 执行cmd,并将stdout存放在output中 |
%alias alias_name cmd | 为系统shell命令定义别名 |
bookmark | 使用IPython的目录书签系统 |
%cd directory | 将系统工作目录更改为directory |
%pwd | 返回系统的当前工作目录 |
%pushd directory | 将当前目录入栈,并转向目标目录 |
%popd | 弹出栈顶目录,并转向目标目录 |
%dirs | 返回一个含有当前目录栈的列表 |
%dhist | 打印目录访问历史 |
%env | 以dict形式返回系统环境变量 |
六、ipython notebook
1、安装 jupyter
jupyter
pip install jupyter
2、运行界面
四、ipython高级用法
一、alias
In [3]: %alias largest ls -1sSh | grep %s
In [4]: largest to
total 42M
20K tokenize.py
16K tokenize.pyc
8.0K story.html
4.0K autopep8
4.0K autopep8.bak
4.0K story_layout.html
注意:别名需要存储的, 否则重启ipython就不存在了:
In [5]: %store largest
Alias stored: largest (ls -1sSh | grep %s)
下次进入的时候%store -r
二、ipcluster - 并行计算
其实ipython提供的方便的并行计算的功能. 先回答ipython做并行计算的特点:
wget http://www.gutenberg.org/files/27287/27287-0.txt
1、第一个版本是直接的, 大家习惯的用法
In [1]: import re
In [2]: import io
In [3]: non_word = re.compile(r'[Wd]+', re.UNICODE)
In [4]: common_words = {
...: 'the','of','and','in','to','a','is','it','that','which','as','on','by',
...: 'be','this','with','are','from','will','at','you','not','for','no','have',
...: 'i','or','if','his','its','they','but','their','one','all','he','when',
...: 'than','so','these','them','may','see','other','was','has','an','there',
...: 'more','we','footnote', 'who', 'had', 'been', 'she', 'do', 'what',
...: 'her', 'him', 'my', 'me', 'would', 'could', 'said', 'am', 'were', 'very',
...: 'your', 'did', 'not',
...: }
In [5]: def yield_words(filename):
...: import io
...: with io.open(filename, encoding='latin-1') as f:
...: for line in f:
...: for word in line.split():
...: word = non_word.sub('', word.lower())
...: if word and word not in common_words:
...: yield word
...:
In [6]: def word_count(filename):
...: word_iterator = yield_words(filename)
...: counts = {}
...: counts = defaultdict(int)
...: while True:
...: try:
...: word = next(word_iterator)
...: except StopIteration:
...: break
...: else:
...: counts[word] += 1
...: return counts
...:
In [6]: from collections import defaultdict # 脑残了 忘记放进去了..
In [7]: %time counts = word_count(filename)
CPU times: user 88.5 ms, sys: 2.48 ms, total: 91 ms
Wall time: 89.3 ms
ipcluster start -n 2 # 好吧, 我的Mac是双核的
2、ipython 并行计算的用法:
In [1]: from IPython.parallel import Client # import之后才能用%px*的magic
In [2]: rc = Client()
In [3]: rc.ids # 因为我启动了2个进程
Out[3]: [0, 1]
In [4]: %autopx # 如果不自动 每句都需要: `%px xxx`
%autopx enabled
In [5]: import os # 这里没autopx的话 需要: `%px import os`
In [6]: print os.getpid() # 2个进程的pid
[stdout:0] 62638
[stdout:1] 62636
In [7]: %pxconfig --targets 1 # 在autopx下 这个magic不可用
[stderr:0] ERROR: Line magic function `%pxconfig` not found.
[stderr:1] ERROR: Line magic function `%pxconfig` not found.
In [8]: %autopx # 再执行一次就会关闭autopx
%autopx disabled
In [10]: %pxconfig --targets 1 # 指定目标对象, 这样下面执行的代码就会只在第2个进程下运行
In [11]: %%px --noblock # 其实就是执行一段非阻塞的代码
....: import time
....: time.sleep(1)
....: os.getpid()
....:
Out[11]: <AsyncResult: execute>
In [12]: %pxresult # 看 只返回了第二个进程的pid
Out[1:21]: 62636
In [13]: v = rc[:] # 使用全部的进程, ipython可以细粒度的控制那个engine执行的内容
In [14]: with v.sync_imports(): # 每个进程都导入time模块
....: import time
....:
importing time on engine(s)
In [15]: def f(x):
....: time.sleep(1)
....: return x * x
....:
In [16]: v.map_sync(f, range(10)) # 同步的执行
Out[16]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [17]: r = v.map(f, range(10)) # 异步的执行
In [18]: r.ready(), r.elapsed # celery的用法
Out[18]: (True, 5.87735)
In [19]: r.get() # 获得执行的结果
Out[19]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
入正题:
In [20]: def split_text(filename):
....: text = open(filename).read()
....: lines = text.splitlines()
....: nlines = len(lines)
....: n = 10
....: block = nlines//n
....: for i in range(n):
....: chunk = lines[i*block:(i+1)*(block)]
....: with open('count_file%i.txt' % i, 'w') as f:
....: f.write('n'.join(chunk))
....: cwd = os.path.abspath(os.getcwd())
....: fnames = [ os.path.join(cwd, 'count_file%i.txt' % i) for i in range(n)] # 不用glob是为了精准
....: return fnames
In [21]: from IPython import parallel
In [22]: rc = parallel.Client()
In [23]: view = rc.load_balanced_view()
In [24]: v = rc[:]
In [25]: v.push(dict(
....: non_word=non_word,
....: yield_words=yield_words,
....: common_words=common_words
....: ))
Out[25]: <AsyncResult: _push>
In [26]: fnames = split_text(filename)
In [27]: def count_parallel():
.....: pcounts = view.map(word_count, fnames)
.....: counts = defaultdict(int)
.....: for pcount in pcounts.get():
.....: for k, v in pcount.iteritems():
.....: counts[k] += v
.....: return counts, pcounts
.....:
In [28]: %time counts, pcounts = count_parallel() # 这个时间包含了我再聚合的时间
CPU times: user 47.6 ms, sys: 6.67 ms, total: 54.3 ms # 是不是比直接运行少了很多时间?
Wall time: 106 ms # 这个时间是
In [29]: pcounts.elapsed, pcounts.serial_time, pcounts.wall_time
Out[29]: (0.104384, 0.13980499999999998, 0.104384)