dfarhi
dfarhi

Reputation: 21

ImportError: cannot import name 'InputDevice' - Evdev

I installed evdev on my Raspberry Pi 3 B+ with sudo -H pip install evdev. The installation went normally and I ran python /usr/local/lib/python2.7/dist-packages/evdev/evtest.py to see if it was working. Everything was fine.

The issue is that when executing this Python code:

from evdev import InputDevice, categorize, ecodes
gamepad = InputDevice('/dev/input/js0')
print(gamepad)
for event in gamepad.read_loop():
  print(categorize(event)

I get this error as an answer:

Traceback (most recent call last):
  File "evdev1.py", line 1, in <module>
    from evdev import InputDevice, categorize, ecodes
  File "/home/pi/Desktop/evdev.py", line 2, in <module>
    from evdev import InputDevice, categorize, ecodes
ImportError: cannot import name 'InputDevice'

But when I execute from evdev import InputDevice, categorize, ecodes on a python shell it seems to work. What am I doing wrong? How can I solve this?

Thankfully, Davi.

Upvotes: 2

Views: 2366

Answers (2)

dtrv
dtrv

Reputation: 753

It's written in your error traceback: You have a file called evdev1.py and a file evdev.py in your working directory. An from evdev import ... in evdev1.py would try to import from the file "/home/pi/Desktop/evdev.py" - which is also a module.

That's why calling from evdev import ... from within another working directory works.

Upvotes: 1

Nick
Nick

Reputation: 780

It's a little confusing, but there are old and new methods of accessing gamepads/joysticks in linux. The older joydev shows devices as "js*" while the newer evdev shows them as "event*"

If you're using evdev, you need to use the event path starting with "/dev/input/event" instead of the one starting with "/dev/input/js".

Identify the device like this:

import evdev
devices = [evdev.InputDevice(path) for path in evdev.list_devices()]
for device in devices:
    print(device.path, device.name)

Or if there is only one, just use the first one that comes along.

import evdev
gamepad = evdev.InputDevice( evdev.list_devices()[0] )

Upvotes: 0

Related Questions