如何在Python中导入库函数"import can"

How to import the library function "import can" in Python

我正在使用 Ubuntu。我想向总线发送垃圾邮件并使用 Wireshark 查看数据包。我尝试 运行 下面显示的 Python 代码,但它引发了以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'can'

我的代码:

import time, can
bustype = 'socketcan'
channel = 'vcan0'
def producer(id):
    # :param id: Spam the bus with messages including the data id.
    bus = can.interface.Bus(channel=channel, bustype=bustype)
    for i in range(10):
        msg = can.Message(arbitration_id=0xc0ffee, data=[id, i, 0, 1, 3, 1, 4, 1], extended_id=False)
        bus.send(msg)
    # Issue #3: Need to keep running to ensure the writing threads stay alive. 
    time.sleep(1)
producer(10)

每当你在Python中得到no module named '<module_name>' error,就意味着python找不到模块。可能是因为缺少模块。

您可以使用 pip 安装 python 个模块。 如果您没有 pip 工具,那么您可以在基于 Debian 的操作系统上使用 sudo apt install python-pip 安装它。

在您的情况下,您需要 python-can 模块,可以使用

安装

pip install python-can

你需要install external third-party package python-can 您可以使用 pip 这样做。按照提供的 link

中的说明进行操作

Ubuntu 18.04 及更高版本

在 Ubuntu 18.04 及更高版本中 python-can 和 python3-can 由默认 Ubuntu 存储库提供。打开终端并输入:

sudo apt update  
sudo apt install python3-can # for Python 3.x  

sudo apt update  
sudo apt install python python-can # for Python 2.x 

要安装 CANard(用于与控制器区域网络 (CAN) 交互的库),您必须使用 pip。

python3 -m pip install --user CANard # for Python 3.x

python -m pip install --user CANard # for Python 2.x