首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >IPython简要入门

IPython简要入门

作者头像
用户2936342
发布2018-08-27 14:32:01
6830
发布2018-08-27 14:32:01
举报
文章被收录于专栏:nummynummy

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赋值

在交互过程中我们可能需要操作底层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
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016.10.10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 获取帮助
  • shell赋值
  • 魔法函数
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档