rocky rocky - 22 days ago 9
Python Question

Given frame or code object, how do I get the associated module file loaded

In a debugger I would like to verify that the source path matches the code that is running. One way to do this in Python 3 is to look at the module byte-compiled file (a

.pyc
or
.pyo
) which has a field for the source size modulo
2**32
.

So now the question is given a frame object how to I find the associated byte-compiled module path. (Again a
.pyc
or
.pyo
file).

print(inspect.getfile(inspect.currentframe()))


will get me a source-file name that I can try to convert to the bytecode module name, but nicer would be if there were a more reliable way since clearly Python had to read the module in the first place.

What's the most reliable way?

Answer

Look at the globals (it's the f_globals attribute of a frame); it has a wealth of info:

  • __name__ - the module name
  • __file__ - the module filename
  • __cached__ - the .pyc bytecode cache filename
Comments