史蒂夫和斯凯 发表于 2017-5-8 09:10:32

PyCon 2011

  本作品采用知识共享署名-非商业性使用-相同方式共享 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 sysclass ExpressionCounter(object):def __init__(self):self.count = 0self.history = []def __call__(self, value):if not self.history or value != self.history[-1]:self.count += 1sys.ps1 = '(%d)> ' % self.countself.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) on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import sys_displayhookinstalling expression counter>>> a = 1>>> 11(1)> 22(2)> 33(3)> a1(4)> a1(4)> a1
页: [1]
查看完整版本: PyCon 2011