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  

你可能感兴趣的:(PyCon 2011 - Hidden Treasures of the Python Standard Library - 自定义交互模式表达式计数器)