python:导入带有错误导入语句的模块=>来自生成的 ImportError 的不详尽信息

发布于 2024-09-02 09:57:44 字数 530 浏览 3 评论 0原文

我有一个有趣的问题想请教你们。

我正在导入一些模块 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

昔梦 2024-09-09 09:57:44

标准库中有 imp 模块,所以你可以这样做:

>>> import imp
>>> imp.find_module('collections')
(<_io.TextIOWrapper name=4 encoding='utf-8'>, 'C:\\Program Files\\Python31\\lib\\collections.py', ('.py', 'U', 1))
>>> imp.find_module('col')
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    imp.find_module('col')
ImportError: No module named col

当找不到模块时,它会引发ImportError。由于它并不尝试导入该模块,因此它完全独立于该特定模块是否会引发 ImportError 。

当然,还有一个 imp.load_module 来实际加载该模块。

There is the imp module in the standard lib, so you could do:

>>> import imp
>>> imp.find_module('collections')
(<_io.TextIOWrapper name=4 encoding='utf-8'>, 'C:\\Program Files\\Python31\\lib\\collections.py', ('.py', 'U', 1))
>>> imp.find_module('col')
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    imp.find_module('col')
ImportError: No module named col

which raises ImportError when module is not found. As it's not trying to import that module it's completely independent on whether ImportError will be raised by that particular module.

And of course there's a imp.load_module to actually load that module.

飘过的浮云 2024-09-09 09:57:44

您还可以查看回溯,可以在代码中检查它。

然而,你为什么想知道——无论哪种方式,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文