Python解釋器和IPython 簡介 Python解釋器 IPython

簡介

今天給大家介紹一下Python的一個功能非常強大的解釋器IPython。雖然Python本身自帶解釋器,但是相對而言IPython的功能更加的強大。

Python解釋器

Python是自帶解釋器的,我們在命令行輸入python即可進入python的解釋器環境:

$> python
Python 2.7.15 (default, Oct  2 2018, 11:47:18)
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.11.45.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> site = "www.flydean.com"
>>> site
'www.flydean.com'
>>>

python解釋器的提示符是>>>

python提供了一個非常有用的命令help,我們可以使用help來查看要使用的命令。

>>> help
Type help() for interactive help, or help(object) for help about object.

在Python3中,還提供了tab的補全功能:

>>> site
'www.flydean.com'
>>> site.
site.capitalize(    site.expandtabs(    site.isalpha(       site.isprintable(   site.lower(         site.rindex(        site.splitlines(    site.upper(
site.casefold(      site.find(          site.isdecimal(     site.isspace(       site.lstrip(        site.rjust(         site.startswith(    site.zfill(
site.center(        site.format(        site.isdigit(       site.istitle(       site.maketrans(     site.rpartition(    site.strip(
site.count(         site.format_map(    site.isidentifier(  site.isupper(       site.partition(     site.rsplit(        site.swapcase(
site.encode(        site.index(         site.islower(       site.join(          site.replace(       site.rstrip(        site.title(
site.endswith(      site.isalnum(       site.isnumeric(     site.ljust(         site.rfind(         site.split(         site.translate(

使用起來非常的方便。

和Python自帶的解釋器之外,還有一個更加強大的解釋器叫做IPython。我們一起來看看。

IPython

IPython是一個非常強大的解釋器,通常它是和jupyter notebook一起使用的。在IPython3.X中,IPython和Jupyter是作爲一個整體一起發佈的。但是在IPython4.X之後,Jupyter已經作爲一個單獨的項目,從IPython中分離出來了。

使用IPython很簡單,輸入IPython命令即可:

$> ipython
Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 12:04:33)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: site= "www.flydean.com"

In [2]: site
Out[2]: 'www.flydean.com'

IPython的提示符是In [1]:

基本上Python自帶的命令在IPython中都是可以使用的。

IPython提供了4個非常有用的命令:

command description
? 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.

魔法函數

IPython中有兩種魔法函數,一種是Line magics,一種是Cell magics

Line magics 接收本行的輸入作爲函數的輸入,是以%開頭的。而Cell magics可以接收多行的數據,直到你輸入空白回車爲止。是以%%開頭的。

比如我們想要看一個timeit的魔法函數的用法,可以使用Object?來表示:

$> In [4]: %timeit?
Docstring:
Time execution of a Python statement or expression

Usage, in line mode:
  %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
or in cell mode:
  %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
  code
  code...

timeit用來統計程序的執行時間,我們分別看下Line magics和Cell magics的使用:

In [4]: %timeit?

In [5]: %timeit range(1000)
199 ns ± 3.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [6]: %%timeit range(1000)
   ...: range(1000)
   ...:
208 ns ± 12.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

事實上,如果只是LIne magics的話,我們可以省略前面的%,但是對於Cell magics來說,是不能省略的。

In [7]: timeit range(1000)

200 ns ± 4.03 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

常見的魔法函數有下面幾種:

運行和編輯

使用%run 可以方便的運行外部的python腳本。

In [8]: run?
Docstring:
Run the named file inside IPython as a program.

Usage::

  %run [-n -i -e -G]
       [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
       ( -m mod | file ) [args]

run有幾個非常有用的參數,比如-t 可以用來統計程序的時間。-d可以進行調試環境,-p可以進行profiler分析。

使用%edit 可以編輯多行代碼,在退出之後,IPython將會執行他們。

如果不想立即執行的話,可以加上-x參數。

Debug

可以使用%debug 或者 %pdb 來進入IPython的調試環境:

In [11]: debug
> /Users/flydean/.pyenv/versions/anaconda3-5.1.0/lib/python3.6/site-packages/IPython/core/compilerop.py(99)ast_parse()
     97         Arguments are exactly the same as ast.parse (in the standard library),
     98         and are passed to the built-in compile function."""
---> 99         return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1)
    100
    101     def reset_compiler_flags(self):

ipdb>
In [12]: pdb
Automatic pdb calling has been turned ON

In [13]: pdb
Automatic pdb calling has been turned OFF

或者可以使用 %run -d theprogram.py 來調試一個外部程序。

History

IPython可以存儲你的輸入數據和程序的輸出數據,IPython的一個非常重要的功能就是可以獲取到歷史的數據。

在交互環境中,一個簡單的遍歷歷史輸入命令的方式就是使用up- 和 down- 箭頭。

更強大的是,IPython將所有的輸入和輸出都保存在In 和 Out這兩個變量中,比如In[4]。

In [1]: site = "www.flydean.com"

In [2]: site
Out[2]: 'www.flydean.com'

In [3]: In
Out[3]: ['', 'site = "www.flydean.com"', 'site', 'In']

可以使用 _ih[n]來訪問特定的input:

In [4]: _ih[2]
Out[4]: 'site'

_i, _ii, _iii 可以分別表示前一個,前前一個和前前前一個輸入。

除此之外,全局變量 _i<n> 也可以用來訪問輸入,也就是說:

_i<n> == _ih[<n>] == In[<n>]
_i14 == _ih[14] == In[14]

同樣的,對於輸出來說也存在着三種訪問方式:

_<n> == _oh[<n>] == Out[<n>]
_12 == Out[12] == _oh[12]

最後的三個輸出也可以通過 _, _____來獲取。

還可以使用%history來列出之前的歷史數據進行選擇。

history可以和 %edit,%rerun,%recall,%macro,%save%pastebin 配和使用:

通過傳入數字,可以選擇歷史的輸入行號。

%pastebin 3 18-20

上面的例子會選擇第3行和第18-20行輸入。

運行系統命令

使用!可以直接運行系統命令:

In [27]: !pwd
/Users/flydean/Downloads

還可以用變量接收運行的結果,比如 : files = !ls

本文作者:flydean程序那些事

本文鏈接:http://www.flydean.com/python-ipython/

本文來源:flydean的博客

歡迎關注我的公衆號:「程序那些事」最通俗的解讀,最深刻的乾貨,最簡潔的教程,衆多你不知道的小技巧等你來發現!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章