I was doing some Trosnoth refactoring recently, and I wanted a tool that would draw import graphs of the Trosnoth subpackages. After a quick search of the Internet didn’t give me what I wanted, I set about to write my own import tools.
Tool Descriptions
- catimports FILE – accepts the name of a Python file and prints all the modules imported by that file.
- whoimports PACKAGE [path] – searches the given path (current directory by default) for Python files which import the given python package.
- makegroup PACKAGE – generates a graph (output as a .dot file) of the imports within the given package or subpackage.
Example
$ catimports settings.py os pygame trosnoth.data trosnoth.utils trosnoth.utils.unrepr trosnoth.version $ whoimports trosnoth.version ./settings.py ./trosnothgui/pregame/playscreen.py ./run/core.py ./trosnothgui/pregame/backdrop.py ./web/server.py ./trosnothgui/interface.py $ python makegraph.py trosnoth $ kgraphviewer imports.dot
The generated imports.dot graph looks something like this:
How it Works
As of Python 2.6, the ast module gives us the ability to walk through the syntax trees of Python code. The tools I wrote use this to find what imports are contained in each Python file.
Getting the Code
I have licensed the code under the MIT license. If may not download, use, modify or redistribute the code unless you agree to the license. The code may be downloaded here.