魔法命令是用于控制notebook的特殊命令。它们运行在代码单元中,以%
或者%%
开头,前者控制单行,后者控制单元。
比如要得到代码运行的时间,可以使用%timeit
;要做代码调试,使用%pdb
。但注意这些命令大多是在Python内核中才可以用,其他内核中大多不适用。更详细的清单请参考https://ipython.readthedocs.io/en/stable/interactive/magics.html
。
使用%lsmagic
可以查看所有支持的魔法命令:
行内魔法命令: %alias %alias_magic %autocall %automagic %autosave %bookmark %cd %clear %cls %colors %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 %popd %pprint %precision %profile %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 单元魔法命令: %%! %%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
?
三个特殊命令之一。 查看帮助文档。
id?
?后面加上魔法命令名,可以查看该命令的说明:
?run
或者与通配符星号*配合,像标准Unix或Windows命令行一样搜索Python命名空间:
import numpy as np np.*load*?
??
三个特殊命令之一。 查看源码。
timeit??
一些C实现的源码,无法查看。
!
三个特殊命令之一。 执行shell命令。
%%! dir
或者直接:
!dir !python --version
注意注意中文和英文感叹符号的差别,别写错了。
再看一些用法示例:
In [3]: !echo "Hello World" Hello World In [4]: files= !ls In [5]: print(files) ['example.jpeg', 'list', 'tmp'] In [6]: directory = !pwd In [7]: print(directory) ['/Users/Parul/Desktop/Hello World Folder'] In [8]: type(directory) IPython.utils.text.SList
%%javascript
插入js代码。
%%javascript alert('haha')
%connect_info
查看用户界面与核心连接的具体信息
{ "shell_port": 8760, "iopub_port": 8761, "stdin_port": 8762, "control_port": 8763, "hb_port": 8764, "ip": "127.0.0.1", "key": "d6ec2510-0ad1dcdb3e08d46dad171d01", "transport": "tcp", "signature_scheme": "hmac-sha256", "kernel_name": "" } Paste the above JSON into a file, and connect with: $> jupyter <app> --existing <file> or, if you are local, you can connect with just: $> jupyter <app> --existing kernel-098ea5bb-a733-48eb-9119-e09a91333ff9.json or even just: $> jupyter <app> --existing if this is the most recent Jupyter kernel you have started.
%qtconsole
jupyter notebook支持三种连接内核的方式:
使用魔法命令%qtconsole
可以打开Qt控制台,如下图所示:
%matplotlib inline
Matplotlib可以内嵌于Jupyter notebook中使用。
要想在Jupyter notebook中使用matplotlib,需要先安装matplotlib 。如果你使用的是Anaconda,那么默认已经安装了。否则可以使用pip install matplotlib
进行安装。
%matplotlib inline import matplotlib.pyplot as plt import numpy as np x = np.arange(20) y = x**2 plt.plot(x, y)
执行结果:
希望老师还能讲讲应用场景,举几个栗子