官术网_书友最值得收藏!

2.4.1 IPython的功能介紹

IPython提供了改進(jìn)的交互式Python Shell,我們可以利用IPython來(lái)執(zhí)行Python語(yǔ)句,并能夠立刻看到結(jié)果,這一點(diǎn)跟Python自帶的Shell工具沒有什么不同,但是IPython額外提供的很多實(shí)用功能是Python自帶的Shell所沒有的,正是這些功能,使得IPython成為眾多Python用戶首選的Shell。

要說(shuō)明的是,下面的演示是以Mac系統(tǒng)下的IPython為例進(jìn)行的(Mac下安裝IPython較簡(jiǎn)單,這里略過(guò))。

·系統(tǒng)版本:Darwin 17.7.0

·Python版本:2.7.10

·IPython版本:5.8.0

1.IPython命令的使用方法

Mac系統(tǒng)下啟動(dòng)IPython的命令為:


Python -m IPython

命令顯示結(jié)果如下:


Python 2.7.10 (default, Oct  6 2017, 22:29:07) 
Type "copyright", "credits" or "license" for more information.

IPython 5.8.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object' for extra details.

In [1]:

魔術(shù)函數(shù)(也可以稱為命令)是IPython提供的一整套命令,用這些命令可以操作IPython本身,以及提供一些系統(tǒng)功能。魔術(shù)命令包括兩種方法:一是行魔術(shù)命令(line magics),以%為前綴,在單個(gè)輸入行上運(yùn)行;二是單元格魔術(shù)命令(cell magics),以%%為前綴,在多個(gè)輸入行上運(yùn)行。

IPython提供了很多類似的魔術(shù)命令,如果你想看都有哪些魔術(shù)命令,可以通過(guò)%lsmagic來(lái)查詢,如果想查詢某個(gè)命令的詳細(xì)信息,可以通過(guò)%cmd?來(lái)獲取,例如:%run?。

另外,默認(rèn)情況下automagic是ON狀態(tài),也就是說(shuō)對(duì)于line-oriented命令我們不需要使用前面的%符號(hào),直接輸入命令即可(例如:cd/root/python),但是對(duì)于cell-oriented命令我們必須輸入%%符號(hào)。

注意

可以通過(guò)%automagic來(lái)打開/關(guān)閉automagic功能,automagic功能打開的時(shí)候,我們輸入命令可以帶上%符號(hào),也可以不帶。

2.IPython功能明細(xì)介紹

下面來(lái)看看IPython強(qiáng)大而實(shí)用的功能。

1)通過(guò)run可直接運(yùn)行程序,比如運(yùn)行/root/python/tt.py文件的命令如下:


In [31]: run /root/python/tt.py

2)擁有TAB自動(dòng)補(bǔ)全功能。使用過(guò)Linux命令行的讀者都應(yīng)該知道TAB鍵自動(dòng)補(bǔ)全有多實(shí)用吧!IPython可以針對(duì)之前輸入過(guò)的變量、對(duì)象的方法等進(jìn)行自動(dòng)補(bǔ)全。我們只需要輸入一部分,就可以看到命名空間中所有相匹配的變量、函數(shù)等,下面通過(guò)圖2-1了解相關(guān)功能。

圖2-1 IPython TAB自動(dòng)補(bǔ)全圖示

TAB鍵還可以針對(duì)文件路徑進(jìn)行補(bǔ)全,比如針對(duì)我們輸入的路徑補(bǔ)全可選路徑。

3)內(nèi)省。在變量的前面或后面加問(wèn)號(hào)(?)就可以查詢某對(duì)象相關(guān)的信息,當(dāng)對(duì)象的描述信息較多時(shí),需要通過(guò)兩個(gè)問(wèn)號(hào)(??)來(lái)顯示全部信息,這在看文件的源碼時(shí)特別適用,比如,我們要查看os模塊的源碼信息,可通過(guò)如下命令實(shí)現(xiàn):


In [57]: import os
In [58]: os??

結(jié)果顯示如下:


Type:        module
String form: <module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
File:        /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py
Source:     
r"""OS routines for NT or Posix depending on what system we're on.

This exports:
    - all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc.
    - os.path is one of the modules posixpath, or ntpath
    - os.name is 'posix', 'nt', 'os2', 'ce' or 'riscos'
    - os.curdir is a string representing the current directory ('.' or ':')
    - os.pardir is a string representing the parent directory ('..' or '::')
    - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
    - os.extsep is the extension separator ('.' or '/')
    - os.altsep is the alternate pathname separator (None or '/')
    - os.pathsep is the component separator used in $PATH etc
    - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
    - os.defpath is the default search path for executables
    - os.devnull is the file path of the null device ('/dev/null', etc.)

Programs that import and use 'os' stand a better chance of being
portable between different platforms.  Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join).
"""

#'

如果我們想查看os.path函數(shù)的使用說(shuō)明,可通過(guò)如下命令實(shí)現(xiàn):


In [60]: os.path?

結(jié)果顯示如下:


Type:        module
String form: <module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
File:        /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py
Docstring:  
Common operations on Posix pathnames.

Instead of importing this module directly, import os and refer to
this module as os.path.  The "os.path" name is an alias for this
module on Posix systems; on other systems (e.g. Mac, Windows),
os.path provides the same operations in a manner specific to that
platform, and is an alias to another module (e.g. macpath, ntpath).

Some of this can actually be useful on non-Posix systems too, e.g.
for manipulation of the pathname component of URLs.

4)執(zhí)行外部系統(tǒng)命令和運(yùn)行外部文件。在IPython中,可以很容易地執(zhí)行外部系統(tǒng)命令和運(yùn)行文件。

使用!符號(hào)可執(zhí)行外部系統(tǒng)命令,比如要用系統(tǒng)命令ls來(lái)查看當(dāng)前目錄中所有以py結(jié)尾的文件,則可以使用如下命令:


In [70]: !ls *.py

顯示結(jié)果如下:


test.py

運(yùn)行外部文件,例如要執(zhí)行/tmp/test.py文件,可以用以下命令來(lái)實(shí)現(xiàn):


!python /tmp/test.py

5)直接編輯代碼。我們可以在IPython命令行下輸入edit命令,edit命令用于啟動(dòng)一個(gè)編輯器。在Linux/Mac系統(tǒng)中會(huì)啟動(dòng)vim編輯器,在Windows系統(tǒng)中則會(huì)啟動(dòng)notepad編輯器。我們可以在編輯器上編輯代碼,保存退出后就會(huì)執(zhí)行相應(yīng)的代碼。

比如我們?cè)趘im編輯器中輸入了如下內(nèi)容:


print 'hello,yhc!'

保存以后關(guān)掉編輯器,IPython將會(huì)立即執(zhí)行這一段代碼,執(zhí)行結(jié)果如下:


IPython will make a temporary file named: /var/folders/qr/8w719nd531j0l4nvdvqlycd80000gn/T/ipython_edit_29b_nF/ipython_edit_XV_OG_.py
Editing... done. Executing edited code...
hello,yhc!
Out[8]: "print 'hello,yhc!'\n"

如果我們只想編輯或修改而不執(zhí)行代碼呢?可以用如下命令實(shí)現(xiàn):


edit -x

6)開啟或關(guān)閉pdb功能。當(dāng)我們打開這個(gè)功能的時(shí)候(通過(guò)%pdb on或者%pdb 1),程序一旦遇到Exception就會(huì)自動(dòng)調(diào)用pdb,進(jìn)入pdb交互界面;如果要關(guān)閉該功能可以通過(guò)%pdb off或者%pdb 0實(shí)現(xiàn)。

7)收集對(duì)象信息。IPython不僅可以用來(lái)管理系統(tǒng),它還提供了多種方法對(duì)Python對(duì)象的信息進(jìn)行查看和收集。

首先,查看系統(tǒng)環(huán)境變量信息。我們可以用env命令來(lái)查看當(dāng)前的系統(tǒng)環(huán)境配置,命令顯示結(jié)果如下:


Out[7]: 
{'Apple_PubSub_Socket_Render': '/private/tmp/com.apple.launchd.tWIX3I6rQu/Render',
    'BDOS_SDK_HOME': '/Users/yuhongchun/data/myproject/bdos_sdk',
    'HOME': '/Users/yuhongchun',
    'HOST_IP': 'docker.for.mac.localhost',
    'LANG': 'zh_CN.UTF-8',
    'LOGNAME': 'yuhongchun',
    'OLDPWD': '/Users/yuhongchun/data/myproject',
    'PATH': '/Library/Frameworks/Python.framework/Versions/3.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Wireshark.app/Contents/MacOS:/Users/yuhongchun/bin/:/Users/yuhongchun/data/myproject/bdos_sdk/bin:/Users/yuhongchun/.ssh/usm',
    'PWD': '/tmp',
    'SECURITYSESSIONID': '186a8',
    'SHELL': '/bin/bash',
    'SHLVL': '1',
    'SSH_AUTH_SOCK': '/private/tmp/com.apple.launchd.5m7rR1eAnL/Listeners',
    'TERM': 'xterm-256color',
    'TERM_PROGRAM': 'Apple_Terminal',
    'TERM_PROGRAM_VERSION': '404',
    'TERM_SESSION_ID': '5A5776D6-41BD-4679-8AAE-2F5E7532D92D',
    'TMPDIR': '/var/folders/qr/8w719nd531j0l4nvdvqlycd80000gn/T/',
    'USER': 'yuhongchun',
    'VERSIONER_PYTHON_PREFER_32_BIT': 'no',
    'VERSIONER_PYTHON_VERSION': '2.7',
    'XPC_FLAGS': '0x0',
    'XPC_SERVICE_NAME': '0',
    '_': '/usr/bin/python',
    '__CF_USER_TEXT_ENCODING': '0x1F5:0x19:0x34'}

執(zhí)行完P(guān)ython程序以后,可以用who或whos打印所有的Python變量,示例如下:


#!/usr/bin/python
import json
jsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

text = json.loads(jsonData)
print text

我們用run執(zhí)行此程序以后,就可以用who或whos打印所有的Python變量了,以下是執(zhí)行下who命令后的顯示結(jié)果:


json  jsonData    text

最后,使用psearch查找當(dāng)前命名空間(namespace)已有的Python對(duì)象。例如我們要查找以json開頭的Python對(duì)象,可以通過(guò)如下命令實(shí)現(xiàn):


In [90]: psearch json*

命令顯示結(jié)果如下:


json
jsonData

8)IPython中常用的其他magic函數(shù)如表2-1所示。

表2-1 IPython中常用的magic函數(shù)說(shuō)明

9)IPython的快捷鍵操作方式易上手。它的常用的快捷鍵操作方式跟Linux下的Bash類似,熟悉Bash操作的讀者應(yīng)該很容易上手,如表2-2所示。

表2-2 IPython快捷鍵組合說(shuō)明

主站蜘蛛池模板: 竹北市| 大理市| 开原市| 偃师市| 万载县| 甘谷县| 宝应县| 华蓥市| 公主岭市| 玉溪市| 五原县| 天门市| 元江| 红原县| 永兴县| 常德市| 云南省| 耒阳市| 明水县| 滁州市| 长白| 克拉玛依市| 勃利县| 太白县| 濮阳县| 鄂尔多斯市| 高清| 民县| 克山县| 庆元县| 斗六市| 济源市| 灵石县| 康马县| 金平| 余干县| 巴林右旗| 北海市| 泰州市| 额敏县| 弋阳县|