Python模块导入错误

4 投票
3 回答
15712 浏览
提问于 2025-04-16 13:04

我正在使用macports来安装各种模块。一般来说,这个方法效果不错,但我遇到了一个错误,解决起来有点困难:

$ python
Python 2.6.6 (r266:84292, Feb 12 2011, 16:57:53) 
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dns
>>> import opcode
>>> from dns import resolver
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/dns/resolver.py", line 26, in <module>
    import dns.message
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/dns/message.py", line 28, in <module>
    import dns.opcode
ImportError: No module named opcode

这可能是路径的问题吗?

>>> import sys
>>> sys.path
['', '/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip', '/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6', '/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin', '/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac', '/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', '/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk', '/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old', '/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload', '/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages', '/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg-info']

$ cat /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/dns/init.py [省略的注释] # init.py 是用于DNS类的。

__version__ = '2.3.3'

import Type,Opcode,Status,Class
from Base import DnsRequest, DNSError
from Lib import DnsResult
from Base import *
from Lib import *
Error=DNSError
from lazy import *
Request = DnsRequest
Result = DnsResult

提前谢谢你们。

3 个回答

0

我正在使用Python 3.7,并且安装了pubdns。这解决了我的问题。
我在使用py3dns、pyDNS(无法安装)、dnspython以及其他很多库时遇到了很大的困难。

2

我卸载了py26-dnspython,然后重新安装了一下。问题就解决了。Fink在freenode上给了这个建议。谢谢他。

8

因为你需要这样做:

from dns import resolver

这样是不行的:

import datetime.datetime

但是这样可以:

from datetime import datetime

如果你要导入一个属于另一个包的包,你需要使用“from”这种写法。

撰写回答