一、IPython解释器
字典解析式:
import numpy as np
data = {i:np.random.randn() for i in range(7)}
1、运⾏Jupyter Notebook
Jupyter Notebook需要与内核互动,内核是Jupyter与其它编程语⾔的交互编程协议。Python的Jupyter内核是使⽤IPython。要启动Jupyter,在命令⾏中输⼊jupyter notebook
jupyter notebook # ⾃动打开默认的浏览器(除⾮指定了--no-browser)
#可以在启动notebook之后,⼿动打开⽹⻚http://localhost:8888/。
# 输⼊⼀⾏Python代码。然后按Shift-Enter执⾏。
%pwd# 查看当前的工作目录
2、Tab补全(ipython和jupyter notebook都可以tab补全)
IPython shell的进步之⼀是其它IDE和交互计算分析环境都有的tab补全功能。在shell中输⼊表达式,按下Tab,会搜索已输⼊变量(对象、函数等等)的命名空间。
要补全以下划线开头的变量或方法时,要先输入一个下划线。
实例功能:可以实例系统路径名、函数参数的关键字参数等
3、自省
变量前后使⽤问号?,可以显示对象的信息,如:
b = [1, 2, 3]
b?# 输出如下:
Type: list
String form: [1, 2, 3]
Length: 3
Docstring:
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
print?# 输出如下:
Docstring:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
Type: builtin_function_or_method
在函数名称后面使用"?"会显示函数的文档字符串
在函数名称后面使用"??"会显示函数的源码
?还有⼀个⽤途,就是像Unix或Windows命令⾏⼀样搜索IPython的命名空间。如下:
import numpy as np
np.*load*?# 输出:
np.__loader__
np.load
np.loads
np.loadtxt
np.pkgload
4、%run命令(ipython或者jupyter notebook下)
⽤%run命令运⾏所有的Python程序。假设有⼀个⽂件ipython_script_test.py
%run ipython_script_test.py
这段脚本运⾏在空的命名空间,⽂件中所有定义的变量),都可以在IPython shell中随后访问,除非执行时发生异常
如果想让⼀个脚本访问IPython已经定义过的变量,可以使⽤%run -i
在Jupyter notebook中,你也可以使⽤%load,它将脚本导⼊到⼀个代码格中。
5、中断运⾏的代码
代码运⾏时按Ctrl-C,如果调用了一些编译的扩展模块,要等到控制返回Python解释器才行
6、从剪贴板执⾏程序
在Jupyter notebook可以将代码复制粘贴到任意代码格执⾏
在IPython shell中也可以从剪贴板执⾏。
使⽤%paste和%cpaste函数。%paste可以直接运⾏剪贴板中的代码
%cpaste功能类似,但会给出⼀条提示,使⽤%cpaste,你可以粘贴任意多的代码再运⾏
7、键盘快捷键(参见下图所示)
8、魔术命令:在指令前添加百分号%前缀
IPython中特殊的命令(Python中没有)被称作“魔术”命令。
许多魔术命令有“命令⾏”选项,可以通过?查看,例如:
%debug?
魔术函数默认可以不⽤百分号,只要没有变量和函数名相同。这