我想使用 Python 的logging
模块在代理启动和关闭时显示消息。atexit
使用模块清理代理。但是,看起来记录器在代理之前被清理了。我怎样才能得到预期的行为?这是一个工作示例:
import atexit
import logging
logging.basicConfig()
LOG = logging.getLogger()
LOG.level = logging.INFO
class Program(object):
def __init__(self):
LOG.info("Hello")
def __del__(self):
LOG.info("Bye")
p = Program()
def cleanup(proxy):
del proxy
atexit.register(cleanup, p)
以及从 shell 运行脚本的输出:
INFO:root:Hello
Exception AttributeError: "'NoneType' object has no attribute 'info'"<bound method Program.__del__ of <__main__.Program object at 0x7f467c9aabd0>>
被忽略
在不同版本和操作系统中具有相同的行为。