Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the path for a failed python import?

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...]

like image 933
Gerrat Avatar asked Jun 01 '12 20:06

Gerrat


People also ask

How do you fix an import error in Python?

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 .

What is Python import path?

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.

What is __ path __ in Python?

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.

Where is Python module path?

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.


1 Answers

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'
like image 53
brandizzi Avatar answered Nov 14 '22 22:11

brandizzi