ctypes 导入在 Python 2.5 上不起作用

5 投票
3 回答
3457 浏览
提问于 2025-04-16 09:04

我正在尝试导入ctypes模块,我使用的是通过macports安装的Python 2.5.5(在Mac OS X 10.6上)。

我遇到了一个错误,提示“ImportError: No module named _ctypes”(具体情况见下面)。我了解到ctypes应该是Python 2.5自带的。有没有什么建议?

谢谢,

Saurabh

错误详情:

$ python
Python 2.5.5 (r255:77872, Nov 30 2010, 00:05:47) 
[GCC 4.2.1 (Apple Inc. build 5659)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ctypes/\_\_init\_\_.py", line 10, in <module>
    from _ctypes import Union, Structure, Array
ImportError: No module named _ctypes

更新:根据Ned的回复,我检查了/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload这个目录。这里没有找到_ctypes.so文件,不过有两个相关的文件在里面:

-rwxr-xr-x  2 root  wheel  136176 Nov 30 00:07 _ctypes_failed.so
-rwxr-xr-x  2 root  wheel   26160 Nov 30 00:05 _ctypes_test.so

这是否意味着我需要重新安装ctypes?

更新2:重新安装Python 2.5解决了这个问题。我不太确定最初的问题是什么。

3 个回答

0

先安装libffi这个东西,然后重新编译Python。

1

最新的Mac OS X自带Python 2.6。你可以试着用这个,而不是用macports。在我的系统上,导入ctypes已经可以正常工作了。

Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes
>>>
1

这可能是文件权限的问题。我手头没有 MacPorts 的 Python 2.5 安装,但根据 MacPorts 的 Python 2.6,应该有一个类似这样的文件:

$ cd /opt/local/Library/Frameworks/Python.framework/Versions/2.5
$ cd ./lib/python2.5/lib-dynload/
$ ls -l _ctypes.so 
-rwxr-xr-x  2 root  wheel  151536 Oct  8 00:26 _ctypes.so*

如果没有,请更新你的问题,提供一下上面提到的 lib-dynload 目录的 ls -l 命令的结果。

更新:根据你提供的额外信息,出现 _ctypes_failed.so 表示在安装 Python 2.5 的过程中,_ctypes 的构建失败了。你可以尝试用详细模式重新安装,看看具体是什么问题:

$ port sudo selfupdate
$ port -v upgrade --force python25

撰写回答