PyCon 2011 - Hidden Treasures of the Python Standard Library - 自定义交互模式表达式计数器...

本作品采用知识共享署名-非商业性使用-相同方式共享 3.0 Unported许可协议进行许可。允许非商业转载,但应注明作者及出处。


作者:liuyuan_jq

2011-03-30


sys.displayhook


默认情况下,如果你在交互模式输入一个表达式,则解释器会调用 print repr(你的表达式)来生成输出结果。从Python 2.1开始,你可以通过设置变量sys.displayhook来改变表达式的输出格式。

自定义交互模式表达式计数器


#!/usr/bin/env python # encoding: utf-8 """Counting expression values. """ import sys class ExpressionCounter(object): def __init__(self): self.count = 0 self.history = [] def __call__(self, value): if not self.history or value != self.history[-1]: self.count += 1 sys.ps1 = '(%d)> ' % self.count self.history.append(value) sys.__displayhook__(value) print 'installing expression counter' sys.displayhook = ExpressionCounter()

演示


Python 2.5.2 (r252:60911, Jan 20 2010, 23:16:55) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys_displayhook installing expression counter >>> a = 1 >>> 1 1 (1)> 2 2 (2)> 3 3 (3)> a 1 (4)> a 1 (4)> a 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值