如何用import语句重写python内置函数?

2024-04-19 12:10:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将print添加到sys.stdout的文本文件中。虽然我知道聪明的人可以想出更优雅、更具Python式的解决方案,但这是我的解决方案

class logger:

  def __init__(self, filename='log.txt'):
    self.logf = open(filename, 'a')

    global print
    self.__print = print

    print = self.lognprint

  def __del__(self):
    self.logf.close()

  def lognprint(self, *args, **keywords):
    self.__print(*args, file = self.logf, **keywords)
    self.__print(*args, **keywords)

如果我在代码中添加了

^{pr2}$

之后print的任何内容也将被记录。在

但由于许多明显的原因,这是不安全的。例如,多个logger对象可能很讨厌。在

此外,我还受到

from __future__ import print_function

(例如,请参见this)并且我想做类似的事情,这样当我import我的模块时,内置的print会被我在代码中的任何地方的print版本覆盖。在

怎么可能?在


Tags: 代码importselfdefstdoutsysargs解决方案
2条回答

不要将代码放在类中,而是将其放在模块级别。这样,它将在第一次导入模块时执行:

# logging.py
print = my_print

一个类似的解决方案,或者将数据记录到一个文件中,该文件还可以打印到标准输出,在logging cookbook中给出。
下面是如何简单地将内容记录到名为'垃圾邮件.log'还可以将某些东西打印到标准输出公司名称:

import logging

logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

在这个例子中,所有的消息都转到文件,只有更高级别的消息转到控制台。在

相关问题 更多 >