CPython since 3.8 already has built-in audit events, including open, so you don't need to patch anything or use anything external. Just add an audit hook with sys.addaudithook().
Quick example:
import inspect
import pathlib
import sys
def callsite():
try:
pathlib.Path("/tmp/file").open()
except:
pass
def audit_hook(event, args):
if event == "open":
path, mode, flags = args
print(f"audit: open({path!r}, {mode!r}, 0o{flags:o})")
# Not using traceback here because traceback will attempt to read the
# source file, causing an infinite recursion of audit events.
f = inspect.currentframe()
while f := f.f_back:
print(
f'File "{f.f_code.co_filename}", line {f.f_lineno}, in {f.f_code.co_name}'
)
def main():
sys.addaudithook(audit_hook)
callsite()
if __name__ == "__main__":
main()
Prints:
audit: open('/tmp/file', 'r', 0o100000000)
File "/path/to/python/lib/python3.12/pathlib.py", line 1013, in open
File "/tmp/audit.py", line 10, in callsite
File "/tmp/audit.py", line 26, in main
File "/tmp/audit.py", line 30, in <module>
Quick example:
Prints: https://docs.python.org/3/library/audit_events.html