How do I find the path for a failed python import?
exception, module, python
Solution
Use the imp module. It has a function, `imp.find_module()`, which receives as a parameter the name of a module and returns a tuple, whose second item is the path to the module:
>>> import imp
>>> imp.find_module('test') # A file I created at my current dir
(<open file 'test.py', mode 'U' at 0x8d84e90>, 'test.py', ('.py', 'U', 1))
>>> imp.find_module('sys') # A system module
(None, 'sys', ('', '', 6))
>>> imp.find_module('lxml') # lxml, which I installed with pip
(None, '/usr/lib/python2.7/dist-packages/lxml', ('', '', 5))
>>> imp.find_module('lxml')[1]
'/usr/lib/python2.7/dist-packages/lxml'
Problem
Let's say I have a module which fails to import (there is an exception when importing it). eg. `test.py` with the following contents: ``` print 1/0 ``` [Obviously, this isn't my actual file, but it will stand in as a good proxy] Now, at the python prompt: ``` >>> import test Traceback (most recent call last): File "<stdin>", line 1, in <module> File "test.py", line 1, in <module> print 1/0 ZeroDivisionError: integer division or modulo by zero >>> ``` What's the best way to find the path/file location of `test.py`? [I could iterate through Python's module search path looking in each directory for the file, but I'd think there must be a simpler way...]