Python 3.8+sysfunction
sys.addaudithook()
auditing
Adds a hook function that the interpreter calls on every audit event: opening a file, importing, spawning a process, calling sys.audit().
Syntax
sys.addaudithook(hook) # hook(event: str, args: tuple)
A hook cannot be removed: it lives until the process exits, and there is deliberately no remove function. It fires very often (every open, import, compile), so filter events by name first and keep the hook fast. An exception raised in the hook cancels the action itself — that can block open, but it is not a sandbox: untrusted code escapes auditing via ctypes and other loopholes.
Examples
import sys
def hook(event, args):
if event.startswith('myapp.'):
print('аудит:', event, args)
sys.addaudithook(hook)
sys.audit('myapp.login', 'alice') # → аудит: myapp.login ('alice',)
import sys
def guard(event, args):
if event == 'open' and str(args[0]).endswith('.secret'):
raise PermissionError('запрещено аудитом')
sys.addaudithook(guard)
try:
open('x.secret', 'w')
except PermissionError as e:
print(e) # → запрещено аудитом
See also
Open in the full glossarydocs.python.orgReport an inaccuracy