内容精简自《利用Python进行数据分析·第2版》第2章 Python语法基础,IPython和Jupyter Notebooks
有一些来自其他地方的收集整理!适用于IPython shell和Jupyter QtConsole
IPython,一个强化的 Python 解释器,或 Jupyter notebooks,一个网页代码笔记本,它原先是 IPython 的一个子项目。
notebook 是 Jupyter 项目的重要组件之一,它是一个代码、文本(有标记或无标记)、数据可视化或其它输出的交互式文档。
Tab补全
IPython shell:
tab补全是字符模式,然后继续tab进入选择,可以用tab、方向键选择,回车确定
notebook:
tab补全是下拉框模式,可以鼠标选择
默认情况下,IPython 会隐藏下划线开头的方法和属性,比如魔术方法和内部的 “私有” 方法和属性,以避免混乱的显示(和让新手迷惑!)这些也可以 tab 补全,但是你必须首先键入一个下划线才能看到它们。如果你喜欢总是在 tab 补全中看到这样的方法,你可以 IPython 配置中进行设置。
还可以补全文件路径
'a:/System Volume Information/'
自省
?
b?
Object `b` not found.
b=[1,2,3]
b?
Type: list
String form: [1, 2, 3]
Length: 3
Docstring:
Built-in mutable sequence.
If no argument is given, the constructor creates a new empty list.
The argument must be an iterable if specified.
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
??
使用??可以显示函数源码,仅对.py有效,python编译字节.pyc、C编译字节.pyd无效
>>>
def add_numbers(a, b):
"""
Add two numbers together
Returns
-------
the_sum : type of arguments
"""
return a + b
>>> add_numbers??
Signature: add_numbers(a, b)
Source:
def add_numbers(a, b):
"""
Add two numbers together
Returns
-------
the_sum : type of arguments
"""
return a + b
File: c:\users\jone\appdata\local\programs\python\python39\scripts\<ipython-input-26-973e9c734ef3>
Type: function
>>> add_numbers?
Signature: add_numbers(a, b)
Docstring:
Add two numbers together
Returns
-------
the_sum : type of arguments
File: c:\users\jone\appdata\local\programs\python\python39\scripts\<ipython-input-26-973e9c734ef3>
Type: function
搜索命名空间,匹配名字
>>> np.*load*?
np.__loader__
np.load
np.loads
np.loadtxt
IPython vs Jupyter QtConsole
-
比IPython shell多了半括号用法提示的功能,而提示内容既是自省的内容
-
比IPython增加了shift+tab 反缩进功能
-
比IPython增加了多窗口设置,以及GUI的各种快捷键
-
IPython是控制台窗口为前端,Jupyter QtConsole是纯python程序,前端是python内置的qt。因此ConEmu对Jupyter QtConsole的支持不好。如果不喜欢浏览器应用、喜欢ConEmu,那么IPython还有玩头
%run
%run a:\helloworld.py
hello world!
%run a:helloworld.py
hello world!
%run a:/helloworld.py
hello world!
确实可以补全路径,但是问题是,如果前面不加引号,他显示的则是命令,而如果前面加了引号,还需要再把引号去除
%run 'a:/helloworld.py'
Exception: File `"'a:/helloworld.py'"` not found.
通过run运行的脚本,其变量仍可以使用,很方便分析
添加-i,则脚本可以使用IPython定义的变量
%load可以加载脚本的内容
i=223261
%run -i a:/printi.py
223261
%load a:/printi.py
# %load a:/printi.py
print(i)
!
执行系统命令
In [3]: ! cmd
Microsoft Windows [版本 10.0.17763.1757]
(