高效使用IPython(一种交互式python开发环境)
作者 easyfly
1 利用tab进行代码自动补全
1.1 代码实例
In[1]: ab=5
In [2]: a
%alias %automagic add2 any
%alias_magic a all apply
%autocall ab an_apple as
%autoindent abs and assert
In [2]: a
2. 利用?显示该函数或者变量的相关信息
2.1 代码实例
In[1]: ab=5
In[2]:ab?
Type: int
String form: 12
Docstring:
int(x[, base]) -> integer
Convert a string or number to an integer, if possible. A floating point
argument will be truncated towards zero (this does not include a string
representation of a floating point number!) When converting a string, use
the optional base. It is an error to supply a base when converting a
non-string. If base is zero, the proper base is guessed based on the
string content. If the argument is outside the integer range a
long object will be returned instead.
2.2 代码实例
In [32]: add2?
Type: function
String form:
File: /Users/huangyifei/mypython/numpy/
Definition: add2(a, b)
Docstring:
3. 利用??显示相关的源代码
3.1 使用说明
在你调用相关的函数的时候,打上两个??,ipython会显示该函数的源代码
3.2 代码实例
In [24]: def add2(a,b):
....: return a+4
....:
In [25]: add2??
Type: function
String form:
File: /Users/huangyifei/mypython/test/
Definition: add2(a, b)
Source:
def add2(a,b):
return a+4
In [26]:
4. 利用通配符 *和? 搜索匹配的函数
4.1 代码实例
In [37]: import numpy
In [38]: numpy.*load*?
numpy.load
numpy.loads
numpy.loadtxt
numpy.pkgload
5. 利用 %run 命令运行脚本文件
5.1 代码实例
In [44]: %run mytest.py
this is a test print
其中,在mytest.py中,内容为:
a='this is '
b='a test print'
print a+b
5.2 使用说明
在运行了%run 之后,所运行的文件中的函数和变量是可见的,在同一个作用域下,可以直接访问
当然也可以运行 %run -i 使得运行的脚本文件有独立的作用域,
6. 暂时中断python函数的运行
6.1 使用说明
利用Ctrl-C即可
##6.2 代码实例
In [29]: [i for i in range(10000000)]
^C---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
in ()
----> 1 [i for i in range(10000000)]
KeyboardInterrupt:
In [30]:
6.3 使用说明
不过如果运行的pyc文件,已经编译好了,那么是没有办法暂时中断的
7 利用%paste 和%cpaste 来运行剪贴板中的文本内容,作为python 代码运行
7.1 代码实例
In[2]: %paste
0
1
2
3
4
其中,剪贴板内容为:
for i in range(5):
print i
print i*10
7.2 使用说明
当然可以用%cpaste 命令来粘贴剪贴板中的代码,然后手动输入--进行运行。
使用%cpaste可以在运行代码之前事先进行纠错检查
同时在运行之前可以按照你需要粘贴任何你想要的代码,然后输入--以及回车进行运行
建议使用%cpaste,少用%paste
关于作者
黄益飞
email:easyfly.huang@gmail.com
参考资料
《利用Python进行数据分析》O'REILLY,机械工业出版社,WestMcKinney,唐学涛翻译
第三章IPython:一种交互式计算和开发环境
本文使用MarkDown进行编辑,感谢http://mahua.jser.me