Search code examples
pythonpython-3.xpython-modulecprofile

Fetch current module while running cProfile


I would like to get ahold of my module (to list all function names), even when using cProfile. How can I do that?

To clarify I'm using some introspection in my own module, but sys.modules[__main__] does of course not return my own module any more when running with -m cProfile.

To reproduce, create modtest.py:

#!/usr/bin/env python3
import sys
print(sys.modules[__name__])

Run it like so:

$ ./modtest.py
<module '__main__' from './modtest.py'>
$ python -m cProfile ./modtest.py
<module 'cProfile' from '...cProfile.py'>

How can I get that last line to say from './modtest.py'?


Solution

  • You won't be able to grab the module object from sys.modules when you provide the module as an argument to cProfile. cProfile doesn't even import the module for you, it just executes it, you wouldn't even be able to grab it from sys.modules after it finished executing.

    When run via the -m switch, __main__ will necessarily point to cProfile, there's no changing that.

    You can always grab the module name from sys.argv[0], import it yourself with importlib and afterwards list the function names.