python:导入带有错误导入语句的模块=>来自生成的 ImportError 的不详尽信息
我有一个有趣的问题想请教你们。
我正在导入一些模块 A,而该模块又导入了一些不存在的模块 B。当然,这会导致 ImportError。
这就是 A.py 的样子
import B
现在让我们导入 A
>>> import A
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/tmp/importtest/A.py", line 1, in <module>
import B
ImportError: No module named B
好吧,解决问题。在不查看错误的字符串表示形式的情况下,我如何知道此 ImportError 是由导入 A 还是由 A 内的某些损坏的导入引起的。
区别在于 A 不存在或者存在不正确的导入语句。
希望你能帮助我...
干杯 bb
I have a funny problem I'd like to ask you guys ('n gals) about.
I'm importing some module A that is importing some non-existent module B. Of course this will result in an ImportError.
This is what A.py looks like
import B
Now let's import A
>>> import A
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/tmp/importtest/A.py", line 1, in <module>
import B
ImportError: No module named B
Alright, on to the problem. How can I know if this ImportError results from importing A or from some corrupt import inside A without looking at the error's string representation.
The difference is that either A is not there or does have incorrect import statements.
Hope you can help me out...
Cheers bb
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
标准库中有
imp
模块,所以你可以这样做:当找不到模块时,它会引发
ImportError
。由于它并不尝试导入该模块,因此它完全独立于该特定模块是否会引发 ImportError 。当然,还有一个
imp.load_module
来实际加载该模块。There is the
imp
module in the standard lib, so you could do:which raises
ImportError
when module is not found. As it's not trying to import that module it's completely independent on whetherImportError
will be raised by that particular module.And of course there's a
imp.load_module
to actually load that module.您还可以查看回溯,可以在代码中检查它。
然而,你为什么想知道——无论哪种方式,A 都行不通。
You can also look at the back-trace, which can be examined in the code.
However, why do you want to find out - either way A isn't going to work.