[英]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: test.py
具有以下内容:
print 1/0
[Obviously, this isn't my actual file, but it will stand in as a good proxy] [显然,这不是我的实际文件,但是它将作为一个很好的代理使用]
Now, at the python prompt: 现在,在python提示符下:
>>> 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
? 找到
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的模块搜索路径,在每个目录中查找文件,但我认为必须有一种更简单的方法...]
Use the imp module. 使用imp模块。 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: 它具有一个函数
imp.find_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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.