Jupyter notebook中5個(gè)有趣的魔法命令
眾?所周知,Jupyter notebook是一個(gè)交互式的Python shell,也就是IPython的封裝版,非常適合用來(lái)進(jìn)行數(shù)據(jù)分析和機(jī)器學(xué)習(xí)。
Jupyter notebook中有很多實(shí)用且鮮為人知的功能,可以實(shí)現(xiàn)有趣的操作,這次舉5個(gè)簡(jiǎn)單的例子。
1、腳本代碼寫入本地文件
%%file方法可以將腳本代碼寫入本地Py文件。
%%file E:\hello.py
def func_inside_script(x, y):
return x + y
print('Hello World')

2、執(zhí)行Py文件
在notebook中可以直接執(zhí)行Py文件,通過(guò)%run方法來(lái)實(shí)現(xiàn)。
%run hello.py

3、監(jiān)測(cè)代碼運(yùn)行時(shí)間
可能你的代碼需要精確的時(shí)間控制,那么%timeit方法可以幫到你。
%timeit [x**2 for x in range(100)]

4、使用系統(tǒng)命令行
在windows中,使用命令行需要打開cmd窗口,如果你使用notebook,則可以通過(guò)!方法輕松執(zhí)行命令行代碼。
# 新建文件夾
my_dir = 'new_dir'
!mkdir $my_dir
5、快速debug
bug是讓人頭疼的事,在notebook中可以輕松進(jìn)行debug,使用%debug命令即可。
def some_func():
var = 'hello world'
for i in range(5):
print(i)
i / 0
return 'finished'
%debug
some_func()

Jupyter notebook中還有很多有趣的魔法命令,感興趣可以多摸索下。
參考:python reference

加入知識(shí)星球【我們談?wù)摂?shù)據(jù)科學(xué)】
500+小伙伴一起學(xué)習(xí)!
· 推薦閱讀 ·
評(píng)論
圖片
表情
