import _testcapi import os import tracemalloc FD_DOMAIN = 1 # size parameter for tracemalloc_track() FD_SIZE = 1 _os_open = os.open _os_close = os.close def open(*args, **kw): fd = _os_open(*args, **kw); _testcapi.tracemalloc_track(FD_DOMAIN, fd, FD_SIZE) return fd def close(fd): _os_close(fd) _testcapi.tracemalloc_untrack(FD_DOMAIN, fd) def monkey_patch(): os.open = open os.close = close def main(): monkey_patch() tracemalloc.start(10) fd = os.open(__file__, os.O_RDONLY) tb = _testcapi.tracemalloc_get_traceback(FD_DOMAIN, fd) tb = tracemalloc.Traceback(tb) print("fd %s was created at:" % fd) for line in tb.format(): print(line) os.close(fd) assert _testcapi.tracemalloc_get_traceback(FD_DOMAIN, fd) is None if __name__ == "__main__": main()