Jupyter Notebook 常用開關

Jupyter Notebook

  使用Jupyter Notebook之前,需要安裝Anaconda。安裝完成後,就可以打開使用了。Jupyter Notebook的路徑,以及文件默認保存在桌面文件的Administrator中。打開要編譯的文件之後,按Esc + h,便可 查看快捷鍵。最常用的快捷鍵,Ctrl + Enter :執行程序

一、Magic 開關

  Magic 開關有兩大類:line magics(針對全局) 與 cell magics(只針對當前cell塊)。

# 在Jupyter Notebook中輸入%lsmagic,查看所有的開關。
%lsmagic
# 運行結果如下:
Available line magics:
%alias  %alias_magic  %autoawait  %autocall  %automagic  %autosave  %bookmark  %cd  %clear  %cls  %colors  %conda  %config  
%connect_info  %copy  %ddir  %debug  %dhist  %dirs  %doctest_mode  %echo  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  
%ldir  %less  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %macro  %magic  %matplotlib  
%mkdir  %more  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %pip  %popd  %pprint  %precision  %prun  
%psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %ren  %rep  %rerun  
%reset  %reset_selective  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  
%who_ls  %whos  %xdel  %xmode

Available cell magics:
%%!  %%HTML  %%SVG  %%bash  %%capture  %%cmd  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%markdown  %%perl  %%prun  
%%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile

Automagic is ON, % prefix IS NOT needed for line magics.
# 在Jupyter Notebook中輸入%quickref,查看上述所有開關的具體功能。
%quickref

1、Line Magic

(1)%config
  用來配置功能的開關,在輸入 Jupyter Notebook 中輸入%config後,按Tab鍵選擇功能。

# 在Jupyter Notebook中,默認只輸出最後一條語句,打開下面開關,每次運行可以輸出所有的語句。
%config ZMQInteractiveShell.ast_node_interactivity='all'
a = 'www.baidu.com'
b = 5
a
b
# 輸出結果如下:
'www.baidu.com'
5

(2)%whos
  查看當前命名空間下有那些名字。

# 在Jupyter Notebook中,輸入%whos,查看當前所有空間名字,不分先後順序,只看執行順序。
a='julyedu.com'
b=5
def myfun1():
    pass
%whos
# 輸出如下:
Variable   Type        Data/Info
--------------------------------
a          str         julyedu.com
b          int         5
myfun1     function    <function myfun1 at 0x000001785D449828>

(3)%reset
  清空命名空間。

%reset

(4)%matplotlib inline
  在Jupyter Notebook如果沒有 %matplotlib inline ,則程序畫出來的圖只會以對象的形式存儲在空間中,不會呈現出來。

%matplotlib inline
import numpy as np
from matplotlib import pyplot as plt

ys = 200 + np.random.randn(100)
x = [x for x in range(len(ys))]

plt.plot(x, ys, '-')
plt.fill_between(x, ys, 195, where=(ys > 195), facecolor='g', alpha=0.6)

plt.title("Fills and Alpha Example")
plt.show()

輸出結果如下:
在這裏插入圖片描述

2、Cell Magic

(1)%%timeit 50
  執行下述代碼50次,給出平均值。

%%timeit 50
for item in range(100):
    a=item
    del a
# 輸出結果如下:
2.94 µs ± 153 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

(2)%%time
  代碼執行一次所花費的時間。

%%time
for item in range(100000):
    a=item
    del a
# 輸出結果如下:
Wall time: 21 ms

(3)%%SVG
  用來畫矢量圖。

%%SVG
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 450 400" width="500" height="200">
  <rect x="80" y="60" width="250" height="250" rx="20" style="fill:red; stroke:black; fill-opacity:0.7" />
  <rect x="280" y="110" width="250" height="250" rx="40" style="fill:blue; stroke:black; fill-opacity:0.5;" />
</svg>

輸出結果如下:
在這裏插入圖片描述
(4)%%javascript
  用來寫javascript代碼。

%%javascript
alert("hey");

輸出效果如下:
在這裏插入圖片描述
(5)%%html
  編寫html。

%%html
<table>
    <tr>
        <th>Header 1</th>
        <th>Header 2</th>
    </tr>
    <tr>
        <td>row 1, cell 1</td>
        <td>row 1, cell 2</td>
    </tr>
    <tr>
        <td>row 2, cell 1</td>
        <td>row 2, cell 2</td>
    </tr>
</table>
<marquee style='width: 30%; color: blue;'>
    <b>Hey There!!!</b>
</marquee>

輸出效果如下:
在這裏插入圖片描述
(6)%%writefile
  新建一個文件,並寫入代碼。使用時,%%writefile + 文件全名。

%%writefile a.py
for item in range(10):
    print(item)

(7)%%system
  調用系統命令,其中dir爲參看系統文件。

%%system
dir

(8)!dir
  與輸入上述 %%system + dir 一個效果,可直接輸入。

!dir

(9)!python
  使用系統命令,相當於在cmd中使用python。使用時,前面加 (!)。

# 在jupyter notebook中輸入:!python a.py,爲執行a.py文件。
!python a.py
# 相當於在cmd中輸入:python a.py,也是執行a.py文件。
python a.py

二、Jupyter Notebook擴展

(1)擴展功能的添加
在這裏插入圖片描述  首先,打開cmd命令窗口或者Ananoconda自帶命令窗口。
建議輸入:

pip install jupyter_contrib_nbextensions  -i https://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host pypi.tuna.tsinghua.edu.cn

  然後,按下回車鍵。
  最後,同樣在命令窗口中輸入:

jupyter contrib nbextension install --user --skip-running-check

按下回車鍵,重新打開jupyter notebook即可。

【注意】如果按照普通pip安裝,直接輸入:python -m pip install jupyter_contrib_nbextensions 極大的可能會因爲網速原因,出現警告,最後報錯。默認的安裝路徑,網速非常慢。國內有幾個很快的鏡像路徑。上面的安裝,選擇的是清華的鏡像安裝路徑。

國內其他網站的鏡像安裝路徑:
  清華大學:https://pypi.tuna.tsinghua.edu.cn/simple/
  中國科技大學:https://pypi.mirrors.ustc.edu.cn/simple/
  中國科學技術大學:http://pypi.mirrors.ustc.edu.cn/simple/
  阿里雲:http://mirrors.aliyun.com/pypi/simple/
  豆瓣:http://pypi.douban.com/simple/

安裝其他擴展包,可以用下面方式進行替換:
在這裏插入圖片描述

相同的方式添加其他擴展包安裝

  • 添加對R語言的支持
  • 添加對Julia語言的支持
  • 添加對C的支持

三、Jupyter Notebook中Python的兩種運行方式

  python有兩種運行方式,第一種是交互式,另一種是腳本式。腳本(Script)是一種批處理文件的延伸,是一種純文本保存的程序,一般來說的計算機腳本程序是確定的一系列控制計算機進行運算操作動作的組合,在其中可以實現一定的邏輯。
  腳本式舉例:

# 代碼在jupyter notebook中輸入。
%%writefile test.py
import sys
# 參數sys.argv[0]爲文件名,參數sys.argv[1]控制執行次數。
print('the file run name ',sys.argv[0],'The time that file should run:',sys.argv[1])
for i in range(int(sys.argv[1])):
    print(i,'times run')

# 調用時,在jupyter notebook中輸入下面符號,調用系統命令,test.py爲文件名,2爲執行次數。
!python test.py 2

交互式:
  選中要執行的代碼塊。直接點擊點擊Run,或者快捷鍵Ctrl + Enter 即可。

四、Jupyter Notebook中python包和模塊的導入

  • 模塊:一個模塊就是一個Python源碼文件(也可能是對c語言文件編譯生成的pyd文件)。
  • 包:組織一堆相關功能的模塊,幷包含__init__.py文件的目錄。

導入模塊

# 首先寫一個代碼模塊,一個模塊本質上是一個py文件。
%%writefile m.py
a=123
_b='str'#
def m_fun():
    return globals()
# 導入模塊
import m
m.__name__
# 返回模塊名字:m
__name__
# 返回:__main__

一個模塊被多次導入一個程序中時:

#一個進程只對應一個模塊的實例,無論被導入多少次,每個模塊在整個解釋器進程僅有一個實例存在。
#在不同的命令行窗口,不同的notebook是不同的解釋器進程。
for i in range(5):
    import os   # 導入5次相同的模塊
    print(id(os))
# 返回結果:
2224424224392
2224424224392
2224424224392
2224424224392
2224424224392
#reload也是一樣,此函數爲重新加載模塊,無論刷新加載多少次,模塊的地址始終是一個。
for i in range(5):
    import os
    print(id(reload(os)))
# 返回結果:
2224424224392
2224424224392
2224424224392
2224424224392
2224424224392

模塊名爲__main__ ?
  正常情況下模塊名name爲對應的文件名,但當模塊作爲程序入口時,name被修改名main,因此使用if name=’main’:實現自適應。

if __name__=='__main__':
    dosomething

導入包
  import + 包的名字

# Python之禪
import this
# 查看系統模塊清單
import sys
list(sys.modules.keys())
# 爬蟲爬谷歌的網頁
import requests
r=requests.get('http://www.google.com')
html_code=r.text
# 創建一個文件夾
import os
os.system('mkdir os_test')

五、使用幫助文檔

str1='julyEdu.com'
# 查看字符串rjust的功能,?這種形式只能在jupyter notebook中使用,可用下面兩種情況。
str1.rjust?
?exec
# help這種形式可用去其它集成開發環境。
help(exec)
  • shift-tab(查看功能的快捷鍵)
    選中一個方法,按shift + tab鍵,即可查看此方法的功能說明。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章