IPython增强了python自带的Console的功能,下面的语法只在IPython中有效。
使用问号获取全局帮助信息。
In [1]: ?
在对象前面或者后面加上?来获取对象的相关帮助信息:
In [6]: object?
Docstring: The most base type
Type: type
使用??可以获取对象的详细信息,甚至会直接打印源码信息:
In[1]: import collections
In[2]: collection.Counter??
Init signature: collections.Counter(*args, **kwds)
Source:
class Counter(dict):
'''Dict subclass for counting hashable items. Sometimes called a bag
or multiset. Elements are stored as dictionary keys and their counts
are stored as dictionary values.
>>> c = Counter('abcdeabcdabcaba') # count elements from a string
>>> c.most_common(3) # three most common elements
[('a', 5), ('b', 4), ('c', 3)]
>>> sorted(c) # list all unique elements
['a', 'b', 'c', 'd', 'e']
>>> ''.join(sorted(c.elements())) # list elements with repetitions
'aaaaabbbbcccdde'
...
还可以使用*进行模糊查询:
In [24]: *int*?
FloatingPointError
int
print
在交互过程中我们可能需要操作底层shell,IPython通过使用!来支持。 例如,显示当前路径
In[1]: !pwd
/User/home/
改变当前目录:
In[1]: !cd /var/etc
或者编辑文件:
In[1]: !vim myfile.txt
在IPython的命令行中还可以使用$variable或者{variable}的方式来引用变量,例如:
In[1]: file = 'myfile.txt'
In[2]: !mv $file {file.upper()}
shell命令也可以出现在!=右边,这种情况下命令的结果将赋值给左边的对象。
In[1]: my_files != ls
还可以组合使用:
my_files =! ls ~/
b = "backup file"
for i,file in enumerate(my_file):
raw = !echo $backup $file
!cp $file {file.split('.')[0]+'.bak'}
IPython还提供了一些特殊的魔法函数,它们的语法与shell类似,但是底层还是Python实现的。
魔法函数以%或者%%开始。
以单个%开始的魔法函数必须位于同一行。
In[1]: %xmode
Exception reporting mode: Verbose
并且支持赋值操作:
In [1]: results = %timeit -r1 -n1 -o list(range(1000))
1 loops, best of 1: 21.1 µs per loop
In [2]: results
Out[2]: <TimeitResult : 1 loops, best of 1: 21.1 µs per loop>
以两个%开始的魔法函数支持跨行,但是不支持赋值操作。
In[1]: %%bash
... : echo "My shell is:" $SHELL
... : echo "My disk usage is:"
... : df -h
My shell is: /usr/local/bin/bash
My disk usage is:
Filesystem Size Used Avail Capacity iused ifree %iused Mounted on
/dev/disk1 233Gi 216Gi 16Gi 94% 56788108 4190706 93% /
devfs 190Ki 190Ki 0Bi 100% 656 0 100% /dev
map -hosts 0Bi 0Bi 0Bi 100% 0 0 100% /net
map auto_home 0Bi 0Bi 0Bi 100% 0 0 100% /hom