使用Jupyter Notebook之前,需要安装Anaconda。安装完成后,就可以打开使用了。Jupyter Notebook的路径,以及文件默认保存在桌面文件的Administrator中。打开要编译的文件之后,按Esc + h,便可 查看快捷键。最常用的快捷键,Ctrl + Enter :执行程序。
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)%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()
(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");
%%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
(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/
例如:pip install 包名 -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
相同的方式添加其他扩展包安装
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 即可。
导入模块
# 首先写一个代码模块,一个模块本质上是一个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)