Trace Python imports

PythonDebuggingImportTrace

Python Problem Overview


My Python library just changed it's main module name from foo.bar to foobar. For backward compat, foo.bar still exists, but importing it raises a few warnings. Now, it seems some example program still imports from the old module, but not directly.

I'd like to find the erroneous import statement. Is there any tool that allows me to trace imports and find the culprit without wading through all of the code?

Python Solutions


Solution 1 - Python

Start the python interpreter with -v:

$ python -v -m /usr/lib/python2.6/timeit.py
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# /usr/lib/python2.6/site.pyc matches /usr/lib/python2.6/site.py
import site # precompiled from /usr/lib/python2.6/site.pyc
# /usr/lib/python2.6/os.pyc matches /usr/lib/python2.6/os.py
import os # precompiled from /usr/lib/python2.6/os.pyc
import errno # builtin
import posix # builtin
# /usr/lib/python2.6/posixpath.pyc matches /usr/lib/python2.6/posixpath.py
import posixpath # precompiled from /usr/lib/python2.6/posixpath.pyc
# /usr/lib/python2.6/stat.pyc matches /usr/lib/python2.6/stat.py
import stat # precompiled from /usr/lib/python2.6/stat.pyc
# /usr/lib/python2.6/genericpath.pyc matches /usr/lib/python2.6/genericpath.py
import genericpath # precompiled from /usr/lib/python2.6/genericpath.pyc
# /usr/lib/python2.6/warnings.pyc matches /usr/lib/python2.6/warnings.py
import warnings # precompiled from /usr/lib/python2.6/warnings.pyc
# /usr/lib/python2.6/linecache.pyc matches /usr/lib/python2.6/linecache.py
import linecache # precompiled from /usr/lib/python2.6/linecache.pyc
# /usr/lib/python2.6/types.pyc matches /usr/lib/python2.6/types.py
import types # precompiled from /usr/lib/python2.6/types.pyc
# /usr/lib/python2.6/UserDict.pyc matches /usr/lib/python2.6/UserDict.py
...

Then just grep for your old module.

Solution 2 - Python

edit foo.bar module, add following code:

import pdb
pdb.set_trace()

when foo.bar be imported, program will stop at pdb.set_trace() in pdb mode, where you can debug your code. For example, you can use "w" command to print the full calling stack.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFred FooView Question on Stackoverflow
Solution 1 - PythonTorsten MarekView Answer on Stackoverflow
Solution 2 - PythonHYRYView Answer on Stackoverflow