How to find a path for failed python import?

Let's say I have a module that cannot be imported (there is an exception when importing).

eg. test.py with the following contents:

 print 1/0 

[Obviously, this is not my actual file, but it will stand like 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 is the best way to find the location of the path / file of test.py ?

[I could scroll through the Python module search path by looking in each directory for the file, but I think there should be an easier way ...]

+6
source share
1 answer

Use the imp module. It has a function imp.find_module() , which takes the module name as a parameter and returns a tuple, the second item of which is the module path:

 >>> 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' 
+14
source

Source: https://habr.com/ru/post/917219/


All Articles