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)
相關文章
相關標籤/搜索