Search code examples
pythoninstallationimporterror

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


I am using Ubuntu. I want to spam the bus and view the packets using Wireshark. I tried to run the Python code shown below, but it threw the following error:

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

My code:

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)

Solution

  • Ubuntu 18.04 and later

    In Ubuntu 18.04 and later python-can and python3-can are provided by the default Ubuntu repositories. Open the terminal and type:

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

    or

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

    To install CANard (Library for interacting with Controller Area Network (CAN)) you must use pip.

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

    or

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