Ipython使用指南

1、简介

  2001年,Fernando Perez为了获得一个更为高效的交互式Python解释器而启动的一个项目,IPython不只仅是一个增强版的shell,他能够直接进行绘图操做的GUI控制台,一个基于web的交互式笔记本,以及一个轻量级的快速并行计算引擎。html

  ipython是一个升级版的交互式python命令行工具.python

2、ipython安装

  1、在已有Python环境安装

pip install ipython
  等到命令执行完成后显示表示完装成功,以下图
successfully

  

  安装完,在命令提示符下输入ipython就能够启动ipython了linux

  其与原版python命令行工具不一样在于ipython的提示符变成了in和out.web

  in为输入命令的地方,out为命令执行完成后输出的地方shell

  

3、ipython经常使用操做

  1、tab键自动补全一些经常使用的方法

  

  一、经常使用命令

1 启动:ipython/ipython qtconsole –pylab=inline 2 Tab键自动补全

  2、系统命令

  一、支持一些系统命令

In [2]: pwd             # 显示当前所在目录
    Out[2]: '/root' In [3]: cd ..           # 返回当前目录的上一级目录
    /

  二、执行系统命令(!)

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

  3、内省(?)

  在变量名或命令的前面或后面加一个 “?” 并执行,能够用于显示该对象的一些通用信息,如对象类型、文档字符串等,这就叫作对象内省。这种操做查看到的信息,尤为是函数和类的信息,比一般直接引用变量名而后回车所看到的(repr)要好。“?” 的另外一个用法是能够搜索 IPython 的命名空间,配合通配符使用效果以下:异步

In [1]:import numpy as np In [2]:np.load? np.load np.loads np.loadtxt np.pkgload 

  使用双问号“??”还能够查看对象的源代码(若是可见的话)。函数

  4、经常使用快捷键

 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 清屏

  5、魔术命令

  在 IPython 的会话环境中,全部文件均可以经过 %run 命令来当作脚本执行,而且文件中的变量也会随即导入当前命名空间。即,对于一个模块文件,你对他使用 %run 命令的效果和 from module import * 相同,除非这个模块文件定义了 main 函数(if name == ‘main:’),这种状况下 main 函数还会被执行。工具

  这种以 % 开头的命令在 IPython 中被称为魔术命令,用于增强 shell 的功能。经常使用的魔术命令有:oop

 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。测试

  一、测试代码的执行时间:

  %time和%timeit

  二、目录书签系统( 对目录作别名)

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'

  三、记录历史输入和输出

  IPython可以记录整个控制台会话,包括输入和输出。执行%logstart便可开始记录日志。IPython的日志功能能够在任什么时候刻开启,它将记录你的整个会话(包括此前的命令)。此外还能够看看几个与之配套的魔术命令%logoff,%logon,%logstate以及%logstop。

  四、与操做系统交互(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形式返回系统环境变量

  6、ipython notebook

  一、安装jupyter

pip install jupyter

  二、运行界面

  

  

  

4、ipython高级用法

  1、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

  2、ipcluster - 并行计算

  其实ipython提供的方便的并行计算的功能. 先回答ipython作并行计算的特色:

wget http://www.gutenberg.org/files/27287/27287-0.txt

  一、第一个版本是直接的, 你们习惯的用法

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

  ipython运行一下

ipcluster start -n 2 # 好吧, 个人Mac是双核的

  二、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)
相关文章
相关标签/搜索