為什麼我喜歡使用 IPython shell 和 Jupyter 筆記本

Jupyter 項目最初是以 IPython 和 IPython 筆記本的形式出現的。它最初是一個專門針對 Python 的互動式 shell 和筆記本環境,後來擴展為不分語言的環境,支持 Julia、Python 和 R 以及其他任何語言。

IPython 是一個 Python shell,類似於你在命令行輸入 python
或者 python3
時看到的,但它更聰明、更有用。如果你曾經在 Python shell 中輸入過多行命令,並且想重複它,你就會理解每次都要一行一行地滾動瀏覽歷史記錄的挫敗感。有了 IPython,你可以一次滾動瀏覽整個塊,同時還可以逐行瀏覽和編輯這些塊的部分內容。

它具有自動補全,並提供上下文感知的建議:

它默認會整理輸出:

它甚至允許你運行 shell 命令:

它還提供了一些有用的功能,比如將 ?
添加到對象中,作為運行 help()
的快捷方式,而不會破壞你的流程:

如果你使用的是虛擬環境(參見我關於 virtualenvwrapper 的帖子),可以在環境中用 pip
安裝:
pip install ipython
要在全系統範圍內安裝,你可以在 Debian、Ubuntu 或樹莓派上使用 apt
:
sudo apt install ipython3
或使用 pip
:
sudo pip3 install ipython
Jupyter 筆記本
Jupyter 筆記本將 IPython shell 提升到了一個新的高度。首先,它們是基於瀏覽器的,而不是基於終端的。要開始使用,請安裝 jupyter
。
如果你使用的是虛擬環境,請在環境中使用 pip
進行安裝:
pip install jupyter
要在全系統範圍內安裝,你可以在 Debian、Ubuntu 或樹莓派上使用 apt
:
sudo apt install jupyter-notebook
或使用 pip
:
sudo pip3 install jupyter
啟動筆記本:
jupyter notebook
這將在你的瀏覽器中打開:

你可以使用 「New」 下拉菜單創建一個新的 Python 3 筆記本:

現在你可以在 In[ ]
欄位中編寫和執行命令。使用 Enter
在代碼塊中換行,使用 Shift+Enter
來執行:

你可以編輯和重新運行代碼塊,你可以重新排序、刪除,複製/粘貼,等等。你可以以任何順序運行代碼塊,但是要注意的是,任何創建的變數的作用域都將根據執行的時間而不是它們在筆記本中出現的順序。你可以在 「Kernel」 菜單中重啟並清除輸出或重啟並運行所有的代碼塊。
使用 print
函數每次都會輸出。但是如果你有一條沒有分配的語句,或者最後一條語句沒有分配,那麼它總是會輸出:

你甚至可以把 In
和 Out
作為可索引對象:

所有的 IPython 功能都可以使用,而且通常也會表現得更漂亮一些:

你甚至可以使用 Matplotlib 進行內聯繪圖:

最後,你可以保存你的筆記本,並將其包含在 Git 倉庫中,如果你將其推送到 GitHub,它們將作為已完成的筆記本被渲染:輸出、圖形和所有一切(如 本例):

本文原載於 Ben Nuttall 的 Tooling Tuesday 博客,經許可後重用。
via: https://opensource.com/article/21/3/ipython-shell-jupyter-notebooks
作者:Ben Nuttall 選題:lujun9972 譯者:geekpi 校對:wxy
本文轉載來自 Linux 中國: https://github.com/Linux-CN/archive