Python3.12中audit hook未触发但Jupyter中触发的原因探究
为什么Python 3.12中创建Test对象时audit钩子未触发,仅在Jupyter Notebook中看到输出?
我原本以为创建Test对象时audit函数会被调用,但在Python 3.12的普通环境中运行代码时并未触发该函数,只有在Jupyter Notebook里运行能看到audit输出,想知道原因是什么?
测试代码
import sys def audit(event, args): output = f'{event} with args={args}' print(output) sys.addaudithook(audit) class Test: def __init__(self): pass a = Test()
Jupyter Notebook运行结果
compile with args=<ast. Module object at 0x7f466a6aeb90>,None) exec with args=<code object ‹module› at 0x7f466a63bd70, file "/tmp/ipykernel_27420/3704920664-py", line 1>,) compile with args=<ast.Module object at 0x7f466a6aec10>, None) exec with args=<code object ‹module› at 0x7f466a63bado, file "/ tmp/ipykernel_27420/3704920664-py", line 1>, ) sys._getframe with args=(<frame at 0x7f466a678d40, file '/home/user/.conda/envs/iiv/lib/python3.12/logging/init_.py', line 1616, code findCa object._getattr_ with args=‹frame at 0x7f466aa812a0, file '/home/user/.conda/envs/iiv/lib/python3.12/logging/.init_.py', line 1672, code object _getattr_with args=<frame at 0x7f466a66410, file '/home/user/.conda/envs/iiv/lib/python3.12/logging/init_.py', line 1527, code d object._getattr_with args=<frame at 0x7f466a80d60,file '/home/user/.conda/envs/iiv/lib/python3.12/site-packages/ipykernel/kernelbase.py' object._ getattr_ with args=<frame at 0x7f466a80d60, file '/home/user/.conda/envs/iiv/lib/python3.12/site-packages/ipykernel/kernelbase.py',
原因解析
自定义类实例化不会触发audit钩子
Python的sys.addaudithook只监听预定义的系统级或敏感操作事件,比如模块导入、文件读写、exec/compile执行、系统函数调用等,自定义类的实例化不在默认的audit事件列表中,所以普通Python环境里创建Test对象不会触发audit函数。Jupyter的输出来自自身运行机制
你在Jupyter里看到的audit输出和创建Test对象完全无关。Jupyter执行代码时,会多次调用compile、exec来解析运行单元格代码,内部还会触发sys._getframe、object.__getattr__等系统级操作,这些恰好是audit钩子监听的事件,因此会触发audit函数输出日志。验证方式
在普通Python环境中添加一个会触发audit事件的操作,比如import os,运行后就能看到audit函数被调用,但a = Test()依然不会产生输出,可直接验证上述结论。
内容的提问来源于stack exchange,提问作者Thomas K
相关产品推荐
相关产品推荐

