1,__str__和__repr__的区别

In [1]: class DoubleRep(object):   ...:     def __str__(self):   ...:         return "Hi,I'm a __str__"   ...:     def __repr__(self):   ...:         return "Hi,I'm a __repr"   ...:        ...:     In [2]: dr = DoubleRep()In [3]: print dr------> print(dr)Hi,I'm a __str__In [4]: drOut[5]: Hi,I'm a __repr

使用print输出对象dr时,__str__方法被调用

使用正式字符串表达式dr时,__repr__方法被调用

2,Ipython shell 提示符:In和Out

In [5]: type(In)Out[5]: 
In [6]: type(Out)Out[6]: 
In [7]: print In------> print(In)['\n', u'class DoubleRep(object):\n    def __str__(self):\n        return "Hi,I\'m a __str__"\n]In [8]: print Out------> print(Out){4: Hi,I'm a __repr, 5: 
, 6: 
}

In就是一个列表

Out就是一个字典

3,Tab自动完成

普通python shell需要开启Tab补齐功能

import rlcompleter, readlinereadline.parse_and_bind('tab: complete')

Ipython中Tab不仅可以补齐命令,还能在载入模块时补齐模块名称

4,Ipython配置文件

安装完这个版本的Ipthon后在home目录下会自动创建.ipython目录
其中ipy_user_conf.py是个配置文件

5,魔力函数

以%开始,参数中不包含括号或者引号,例如,%cd mydir
lsmagic 列出所有魔力函数
%<Tab>  同样也是列出所有魔力函数
输入magic可以打开包含所有魔力函数的帮助文档
如何你已经知道某个魔力函数,可以这样来查看帮助 %page ?
%quickref 是一个快速参考文档,包含了对%magic函数的迷你总结

6,alias

即创建一个别名,能够在ipython中运行bash shell命令

In [1]: alias nss netstat -lptnIn [2]: nssActive Internet connections (only servers)Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    tcp        0      0 192.168.122.1:53        0.0.0.0:*               LISTEN      2022/dnsmasq        tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1543/sshd           tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      1546/cupsd          tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1965/master         tcp6       0      0 :::22                   :::*                    LISTEN      1543/sshd           tcp6       0      0 ::1:631                 :::*                    LISTEN      1546/cupsd          tcp6       0      0 ::1:25                  :::*                    LISTEN      1965/master         In [3]: nss | grep 80    #别名后面可以查找某个关键字

如下再提供几个实例:

In [5]: alias achoo echo "|%l|"  #%l就代表了字符串,输出""内所有字符In [6]: achoo                    ||In [7]: achoo these are args|these are args|In [8]: alias achoo echo "%l"    In [9]: achoo these are argsthese are argsIn [16]: alias achoo echo first:"|%s|", second:"|%s|"  #%s代表字符串,有先后顺序In [17]: achoo foo barfirst:|foo|, second:|bar|In [18]: achoo foo bar bam  #输出字符串数量少了会报错,多了会继续输出在尾部first:|foo|, second:|bar| bamIn [20]: store achoo  #保存别名,下次进入ipthon还能继续使用Alias stored: achoo (2, 'echo first:"|%s|", second:"|%s|"')

7,在ipython中另一个执行bash shell命令的方式:!

In [2]: !netstat -lptn

8,保存到变量中使用,输出稍有不同,形式是一个list-like对象

In [4]: l = !ps aux | grep $user | grep $processIn [5]: l

!!和!可以替换,只是使用!!无法保存结果到变量

9,rehash魔力函数会更新PATH路径中的别名表,别名表就是ipython映射别名到shell命令的表格

__IP是一个交互式shell对象,有一个叫alias_table的属性,这里就是映射表的地方

In [7]: __IP.alias_tableOut[7]: {'achoo': (2, 'echo first:"|%s|", second:"|%s|"'), 'cat': (0, 'cat'), 'clear': (0, 'clear'), 'cp': (0, 'cp -i'), 'lc': (0, 'ls -F -o --color'), 'ldir': (0, 'ls -F -o --color %l | grep /$'), 'less': (0, 'less'), 'lf': (0, 'ls -F -o --color %l | grep ^-'), 'lk': (0, 'ls -F -o --color %l | grep ^l'), 'll': (0, 'ls -lF'), 'ls': (0, 'ls -F'), 'lx': (0, 'ls -F -o --color %l | grep ^-..x'), 'mkdir': (0, 'mkdir'), 'mv': (0, 'mv -i'), 'rm': (0, 'rm -i'), 'rmdir': (0, 'rmdir')}

它是字典类型:

In [8]: type(__IP.alias_table)Out[8]: 

它的初始长度:

In [9]: len(__IP.alias_table)Out[9]: 16

使用rehash后,映射就变大了

In [10]: rehashIn [11]: len(__IP.alias_table)Out[11]: 2249

10,rehashx和上面的rehash功能差不多,对比rehash和rehashx差了哪几项

In [4]: from sets import SetIn [5]: rehashx_set = Set(__IP.alias_table.keys())In [6]: rehashIn [7]: rehash_set = Set(__IP.alias_table.keys())In [8]: rehash_set - rehashx_set

11,cd和bash中的cd命令功能一样

cd -  回到前一个目录

cd -q 静默输出:

In [31]: cd /tmp/tmp                In [32]: cd -q /tmp

cd -b t  进入标签所指定的位置 b:bookmark,t:定义的标签

cd -3 数字代表目录历史列表的序号

12,bookmark

创建标签1:

In [1]: cd /tmp/tmpIn [2]: bookmark t

创建标签2:

In [3]: bookmark t /tmp

列出标签:

In [4]: bookmark -lCurrent bookmarks:t -> /tmp

删除标签:

In [9]: bookmark -d alan  #删除单个名称为alan的标签In [22]: bookmark -r  #一次性删除所有标签

13,dhist 显示访问目录的历史记录

cd -<Tab> 差不多的目录历史功能

In [24]: dhistDirectory history (kept in _dh)0: /tmp1: /tmp/VMwareDnD2: /tmp3: /root4: /tmp5: /root6: /tmp7: /root8: /tmp9: /root10: /tmp11: /tmp12: /tmp13: /tmp14: /usr/local/bin
In [26]: dhist 5  #显示5条记录Directory history (kept in _dh)10: /tmp11: /tmp12: /tmp13: /tmp14: /usr/local/bin
In [27]: dhist 3 7  #显示一个范围,7不包含Directory history (kept in _dh)3: /root4: /tmp5: /root6: /tmp

14,python和shell结合使用

In [29]: for i in range(10):      ....:     !date > ${i}.txt  #输出日期到i个文件中

15,用ipython操作进程

调用grep()方法,查找'ipython'的进程条目

In [1]: ps = !ps auxIn [2]: ps.grep('ipython')Out[2]: SList (.p, .n, .l, .s, .grep(), .fields() available). Value:0: root       8978  1.3  1.4 222792 14568 pts/0    S+   13:17   0:00 /usr/bin/python /usr/bin/ipython

列出非root用户的进程

In [3]: ps.grep('root', prune=True)

16,判读文件还是目录

In [1]: import osIn [2]: file_list = !lsIn [3]: file_listIn [4]: file_list.grep(os.path.isfile)Out[4]: SList (.p, .n, .l, .s, .grep(), .fields() available). Value:0: anaconda-ks.cfg1: initial-setup-ks.cfg2: ipython-0.8.2.tar.gzIn [5]: file_list.grep(os.path.isdir)Out[5]: SList (.p, .n, .l, .s, .grep(), .fields() available). Value:0: ipython-0.8.21: 公共2: 模板3: 视频4: 图片5: 文档6: 下载

17,筛选进程中的列,用到fields()方法

In [10]: ps = !ps auxIn [11]: ps.grep('root', prune=True).fields(0,1,8)

先筛选整个ps的第0和第1列,再过滤出postfix用户的第1列

In [12]: ps.fields(0,1).grep('postfix').fields(1)Out[12]: SList (.p, .n, .l, .s, .grep(), .fields() available). Value:0: 24351: 8004

s属性将结果以字符串的形式输出

In [13]: ps.fields(0,1).grep('postfix').fields(1).sOut[13]: '2435 8004'

18,查看系统内部环境变量

[root@study ~]# ipython -p shIPython 0.8.2   [on Py 2.7.5][~]|1> import os[~]|2> os.environ['PATH']   <2> '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin'

19,在结束位置和开始位置添加环境变量值

[~]|3> env PATH+=:/home/alanyaoPATH after append = /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/home/alanyao[~]|4> env PATH-=:/tmpPATH after prepend = :/tmp/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/home/alanyao

ipython可以保证对PATH的修改即时生效

20,显示一下所有能够即时生效的环境变量

[~]|3> env -p   <3> {'add': [('PATH', ':/home/alanyao')], 'pre': [('PATH', ':/tmp')], 'set': {}}

21,删除对PTAH即时生效的设置,如果这里用os.environ['PATH']检查,那些设置还在,重启ipython shell会删除的

[~]|6> env -d PATHForgot 'PATH' (for next session)

22,mglob命令返回一个python列表对象

递归查找所有.cfg文件

[~]|4> mglob rec:*.cfg   <4> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:0: ./anaconda-ks.cfg1: ./initial-setup-ks.cfg2: ./.config/yelp/yelp.cfg3: ./.local/share/telepathy/mission-control/accounts.cfg4: ./.local/share/telepathy/mission-control/accounts-goa.cfg

显示所有目录

[~]|5> mglob dir:*   <5> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:0: 桌面1: 下载2: 模板3: 公共4: 文档5: 音乐6: 图片7: 视频8: ipython-0.8.2

23,page作用和bash中less一样,分页显示

In [2]: p = !ps auxIn [3]: page p

24,pdef打印函数的声明部分

In [3]: def myfunc(a,b,c,d):   ...:     '''return something'''   ...:     return a,b,c,d   ...: In [4]: pdef myfunc myfunc(a, b, c, d)

25,pdoc打印函数的注释部分

In [5]: pdoc myfuncClass Docstring:    return somethingCalling Docstring:    x.__call__(...) <==> x(...)

26,pfile打印出文件的内容

In [6]: import osIn [7]: pfile os

27,pinfo打印出相关信息

#比如:模块In [1]: import some_moduleIn [2]: pinfo some_module#比如:模块的类In [3]: pinfo some_module.Foo#也可以以这种形式In [4]: f = some_module.Foo()In [5]: pinfo f#更可以In [6]: ? fIn [7]: f ?#也可以用??,提供详细的信息In [9]: some_module.Foo ??

28,psource打印模块、模块中类和函数的源代码

In [1]: import some_other_moduleIn [5]: psource some_other_moduleIn [6]: psource some_other_module.FOOIn [7]: psource some_other_module.baz

29,psearch查找python对象

In [9]: psearch c*#或者可以用?代替In [10]: c*?psearch默认搜索路径是builtin和user#-e用来排除In [12]: psearch -e builtin c*#搜索user命名空间中的整数对象In [13]: psearch -e builtin * int#搜索user命名空间中的字符串In [14]: psearch -e builtin * string

30,who函数返回交互定义的对象名称

In [17]: whoa    aa    b    bb    c    cc    In [18]: who inta    b    c    In [19]: who straa    bb    c

who_ls和who差不多,返回的是列表形式

In [20]: who_lsOut[20]: ['a', 'aa', 'b', 'bb', 'c', 'cc']

由于who_ls返回名称列表,使用_variable访问名称列表,只针对最后一次输出

In [22]: who_ls intOut[22]: ['a', 'b', 'c']In [23]: for n in _:   ....:     print n   ....:        ....:     abc

whos打印更详细的列表

In [24]: whosVariable   Type    Data/Info----------------------------a          int     1aa         str     oneb          int     2bb         str     twoc          int     3cc         str     threen          str     c

31,历史功能

搜索返回匹配输入的行
回到行首
回到行末
等同于backupspace键
历史记录行向后移动一行

hist显示历史命令,-n选项可以去掉前面的数字

-t选项似乎和直接使用hist输出功能一样

In [1]: foo = 1In [2]: bar = 2In [3]: bam = 3In [4]: cd /tmp/tmpIn [5]: hist1: foo = 12: bar = 23: bam = 34: _ip.magic("cd /tmp")5: _ip.magic("hist ")

-r选项能够准确显示输入的内容raw history

In [8]: hist -r1: foo = 12: bar = 23: bam = 34: cd /tmp5: hist6: hist -n7: hist -t8: hist -r

-g是一个搜索的标志,可以配合标志进行搜索

In [11]: hist -g b

_代表“上次输出”

In [12]: foo = "foo_string"In [13]: _Out[13]: ''In [14]: fooOut[14]: 'foo_string'In [15]: _Out[15]: 'foo_string'In [16]: a = _In [17]: aOut[17]: 'foo_string'

_加上一个out后的数字,可以直接返回那条out的内容

如下面的:_17

In [17]: aOut[17]: 'foo_string'In [18]: _17Out[18]: 'foo_string'

我们也可以把_17赋值给变量

如:

In [19]: output = _17In [20]: outputOut[20]: 'foo_string'

32,自动和快捷方式
macro宏 例1:

In [1]: dirlist = []In [2]: for f in dirlist:   ...:     print "working on",f   ...:     print "done with",f   ...:     print "moving %s to %s.done" %(f,f)   ...:     print "*" * 40   ...:        ...:     In [3]: macro procdir 2   #注意这里2是代表上面In[2]处Macro `procdir` created. To execute, type its name (without quotes).Macro contents:for f in dirlist:    print "working on",f    print "done with",f    print "moving %s to %s.done" %(f,f)    print "*" * 40In [4]: dirlist = ['a.txt','b.txt','c.txt']In [5]: procdir------> procdir()working on a.txtdone with a.txtmoving a.txt to a.txt.done****************************************working on b.txtdone with b.txtmoving b.txt to b.txt.done****************************************working on c.txtdone with c.txtmoving c.txt to c.txt.done****************************************

macr 例2:

In [3]: for x in range(1,10):   ...:     print x   ...:        ...:     123456789In [4]: macro procdir 3Macro `procdir` created. To execute, type its name (without quotes).Macro contents:for x in range(1,10):    print xIn [5]: procdir------> procdir()123456789

33,store函数可以一直保存变量或者宏在ipython中,关闭ipython也无所谓

比如:
store x
这样变量x就一直保存在ipython中了
store -z 删除所有存储的变量,下次启动ipython后就没了

34,reset函数用来从交互命名空间中删除所有变量

In [1]: a = 1In [2]: b = 2In [3]: c = 3In [4]: whosVariable   Type    Data/Info----------------------------a          int     1b          int     2c          int     3In [5]: resetOnce deleted, variables cannot be recovered. Proceed (y/[n])?  In [6]: whosInteractive namespace is empty.

35,rep 取回最近处理的结果

In [1]: def format_str(s):   ...:     return "str(%s)" % s   ...: In [2]: format_str(1)Out[2]: 'str(1)'In [3]: repIn [4]: str(1)

36,rep还能重复运行多少行到多少行的代码

In [1]: i = 1In [2]: i += 1In [3]: print i------> print(i)2In [4]: rep 2-3lines [u'i += 1\nprint i\n']------> print(i)3In [7]: rep 2-3lines [u'i += 1\nprint i\n']------> print(i)4

37,rep还能重复包含字符的行

In [1]: a = 1In [2]: b = 2In [3]: c = 3In [4]: rep aIn [5]: a = 1