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...]
Python's ImportError ( ModuleNotFoundError ) indicates that you tried to import a module that Python doesn't find. It can usually be eliminated by adding a file named __init__.py to the directory and then adding this directory to $PYTHONPATH .
The easiest way to import a Python module, given the full path is to add the path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.
Packages support one more special attribute, __path__ . This is initialized to be a list containing the name of the directory holding the package's __init__.py before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.
The search path for modules is managed as a Python list saved in sys. path. The default contents of the path include the directory of the script used to start the application and the current working directory. The first directory in the search path is the home for the sample script itself.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With