In the official document said the following code
python -m trace --count -C . somefile.py ...
lists all the modules imported during the execution.
However, I couldn't find any documentation about the programmatic API for doing the same thing inside the code. What I am looking for is not How to list imported Modules?. My concern is listing all the imported modules and imported modules of those imported modules and so on, If and only if for any particular module it is imported on execution path.