01-啓動程序
執行以下命令:
jupyter notebook
[NotebookApp] Serving notebooks from local directory: /home/nanfengpo
[NotebookApp] 0 active kernels
[NotebookApp] The IPython Notebook is running at: http://localhost:8888/
[NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
注意以下幾點:
- 打開地址爲當前bash的目錄,默認的根目錄
- 瀏覽器地址爲http://localhost:8888/
- 通過control -C終止jupyter程序
幾個基本操作:
- 雙擊D:刪除當前cell
- 單擊M:轉爲markdown文檔
- markdown文檔下運行變爲預覽模式
02-IPython的幫助文檔
使用help()
通過以下命令來獲得幫助文檔:
help(len)
Help on built-in function len in module builtins:
len(obj, /) Return the number of items in a container.
使用?
或者使用問號:
len?
Type Markdown and LaTeX: α2α2
還可以應用到自定義的變量和自定義的函數上來返回幫助文檔
此外,使用兩個??可以把函數的源代碼顯示出來
tab自動補全
敲擊tab鍵能自動補全
也可以在import的時候自動補全
03-IPython魔法命令
運行外部Python文件
使用下面命令運行外部python文件(默認是當前目錄,最好加上絕對路徑)
%run *.py
例如在當前目錄下有一個myscript.py文件:
def square(x): “”“square a number”“” return x ** 2
for N in range(1, 4): print(N, “squared is”, square(N))
我們可以通過下面命令執行它:
%run myscript.py
尤其要注意的是,當我們使用魔法命令執行了一個外部文件時,該文件的函數就能在當前會話中使用
運行計時
用下面命令計算statement的運行時間:
%time statement
%time print('Hello AI')
用下面命令計算statement的平均運行時間:
%timeit statement
timeit會多次運行statement,最後得到一個更爲精準的預期運行時間
記住:
- %time一般用於耗時長的代碼段
- %timeit一般用於耗時短的代碼段
查看當前會話中的所有變量與函數
快速查看當前會話的所有變量與函數名稱:
%who
a np p sc sk square
查看當前會話的所有變量與函數名稱的詳細信息:
%whos
返回一個字符串列表,裏面元素是當前會話的所有變量與函數名稱:
%who_ls
執行Linux指令
Linux指令:
echo “hello world” # echo is like Python’s print function hello world pwd # pwd = print working directory /home/jake # this is the “path” that we’re sitting in
ls # ls = list working directory contents notebooks projects mkdir mm /home/jake/projects
$touch txt !touch /home/nanfengpo/Desktop/xx/hello.txt
在Linux指令之前加上 !,即可在ipython當中執行Linux指令。
注意會將標準輸出以字符串形式返回
!echo 'hello'
更多魔法命令
列出所有魔法命令
lsmagic
查看魔法命令的文檔: 使用?
lsmagic
04-notebook的快捷鍵
命令模式
- Enter : 轉入編輯模式
- Shift-Enter : 運行本單元,選中下個單元
- Ctrl-Enter : 運行本單元,選中下個單元
- Alt-Enter : 運行本單元,在下面插入一單元
- Y : 單元轉入代碼狀態
- M :單元轉入markdown狀態
- A : 在上方插入新單元
- B : 在下方插入新單元
編輯模式 ( Enter 鍵啓動)
- Tab : 代碼補全或縮進
- Shift-Tab : 提示 help 以及?/??
- Ctrl-A : 全選
- Ctrl-Z : 復原
05-快速導庫
pip freeze > requirements.txt
sudo pip install - r requirements.txt