Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

python - Import error: you must be root

I'm trying to use the keyboard library in python 3 but continue to get an import error. I ran the program in windows in Thonny and It worked fine but I cant run it in the pi. I tried running it both as root and with sudo command with the same results. Below is the code as well as the error.

import keyboard
import time

x=0

while True:
    print (x)
    x=x+1
    print ("Press t to end program")
    if keyboard.is_pressed('t'):
        break
    else:
        pass

print("I'm done")

Output

0
Press t to end program
Traceback (most recent call last):
File "/home/pi/Desktop/Programs/KeyboardTest.py", line 10, in <module>
if keyboard.is_pressed('t'):
File "/home/pi/.local/lib/python3.5/site-packages/keyboard/__init__.py", line 166, in is_pressed
_listener.start_if_necessary()
File "/home/pi/.local/lib/python3.5/site-packages/keyboard/_generic.py", line 35, in start_if_necessary
self.init()
File "/home/pi/.local/lib/python3.5/site-packages/keyboard/__init__.py", line 116, in init
_os_keyboard.init()
File "/home/pi/.local/lib/python3.5/site-packages/keyboard/_nixkeyboard.py", line 110, in init
build_device()
File "/home/pi/.local/lib/python3.5/site-packages/keyboard/_nixkeyboard.py", line 106, in build_device
ensure_root()
File "/home/pi/.local/lib/python3.5/site-packages/keyboard/_nixcommon.py", line 165, in ensure_root
raise ImportError('You must be root to use this library on linux.')
ImportError: You must be root to use this library on linux.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Very late response, but I had your same problem. Just found a solution. You have to be root to run this program! The "Gotcha" comes, however, to how you installed the keyboard library...

Make sure when you installed the keyboard library that you did a:

sudo pip3 install keyboard

I did not do a sudo and first time I installed it. So what happened is that:

1) you try to run the program without being root

  • the library DOES exist, but you are not root so you get the issue you got

2) you try to run teh program as root

  • But pip3 did not install it for a root user, so you get a "keyboard not recognized".

hope this helped.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...