AttributeError: 'module' object has no attribute 'CAN_RAW'

AttributeError: 'module' object has no attribute 'CAN_RAW'

我正在编写一个简单的 python 脚本来从 CAN 总线读取数据。我将 python_can 库用于 python 2.7。它包含一个名为 CANopenNode 的 class 并且在我写的 __init_ 方法中:

self.bus = can.interface.Bus(channel = 'can0', bustype = 'socketcan_native')

当我 运行 代码时,它报告如下错误:

File "/home/jxu/.local/lib/python2.7/site-packages/can/interface.py", line 87, in __new__
return cls(channel, **kwargs)
File "/home/jxu/.local/lib/python2.7/site-packages/can/interfaces/socketcan/socketcan_native.py", line 416, in __init__
self.socket = create_socket(CAN_RAW)
File "/home/jxu/.local/lib/python2.7/site-packages/can/interfaces/socketcan/socketcan_native.py", line 305, in create_socket
if can_protocol is None or can_protocol == socket.CAN_RAW:
AttributeError: 'module' object has no attribute 'CAN_RAW'

create_socket(库内)中的相关代码行如下所示:

if can_protocol is None or can_protocol == socket.CAN_RAW:
    can_protocol = socket.CAN_RAW
    socket_type = socket.SOCK_RAW
elif can_protocol == socket.CAN_BCM:
    can_protocol = socket.CAN_BCM
    socket_type = socket.SOCK_DGRAM
sock = socket.socket(socket.PF_CAN, socket_type, can_protocol)

库文件好像没有错:

>>> import socket
>>> print socket.__file__
/usr/lib/python2.7/socket.pyc

谁能解释一下这里的 CAN_RAW 是什么意思以及为什么会出现这个错误,谢谢!

您选择了 socketcan_native 公交车:

bustype = 'socketcan_native'

但是,根据 SocketCAN interface documentation,您不能在 Python 2.7 上使用该选项:

There are two implementations of socketcan backends. One written with ctypes to be compatible with Python 2 and 3, and one written for future versions of Python3 which feature native support.

[...]

Unless you’re running Python3.3 or lower the recommended backend is socketcan_native. For Python2.7 and Python3 <3.4, the available backend is socketcan_ctypes.

切换到使用 socketcan_ctypes:

self.bus = can.interface.Bus(channel = 'can0', bustype = 'socketcan_ctypes')

或者,这好多了,使用socketcan界面;这会触发自动检测用于您当前系统的正确接口。

可用的特定 socket.CAN_RAW constant was added in Python 3.3, which is why trying to use socketcan_native fails to find the name in Python 2.7. The socketcan_native implementation also needs socket.CAN_BCM,已在 Python 3.4 中添加。