I'm using a raspberry pi 3A+ and have been trying to use the keyboard for hours. I have written this code:
import keyboard
while True:
if keyboard.is_pressed("a"):
print("You pressed 'a'.")
break
Every time I run it the console just says this long error message:
Traceback (most recent call last):
File "/home/yesnt/Documents/programming/NICK.py", line 3, in <module>
if keyboard.is_pressed("a"):
File "/home/yesnt/.local/lib/python3.9/site-packages/keyboard/__init__.py", line 410, in is_pressed
_listener.start_if_necessary()
File "/home/yesnt/.local/lib/python3.9/site-packages/keyboard/_generic.py", line 35, in start_if_necessary
self.init()
File "/home/yesnt/.local/lib/python3.9/site-packages/keyboard/__init__.py", line 196, in init
_os_keyboard.init()
File "/home/yesnt/.local/lib/python3.9/site-packages/keyboard/_nixkeyboard.py", line 113, in init
build_device()
File "/home/yesnt/.local/lib/python3.9/site-packages/keyboard/_nixkeyboard.py", line 109, in build_device
ensure_root()
File "/home/yesnt/.local/lib/python3.9/site-packages/keyboard/_nixcommon.py", line 174, 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.
I have only started playing with the raspberry today, so I still don't know a lot of things. Can anyone help me fix this? Also I'm trying to use it for a circuit to turn on and off a LED, but I think it won't have any interference on that. Thanks
I've installed the keyboard in every single way shape and form, but nothing. install keyboard, pip install keyboard, pip3 install keyboard, sudo pip3 install keyboard,....
You do not have permission to access raw devices in /dev/input/input*, that is documented in the package you use: https://pypi.org/project/keyboard/
You could run your program as root (sudo myProgram.py) or check the permission of the input devices this script want to access. I checked my linux machine and the devices are owned by root and group input, so it could be a solution to add the group input to your user. But you have to check the permission on YOUR raspberry pi.
Related
I have a python script, using pygame and pyautogui which works when run through terminal or any IDLE on my Raspberry Pi 3 Model B V1.2. The script opens a webpage, and reads joystick inputs through pygame.
I want the script to run at boot after a network is connected, so have created a service in /etc/systemd/system/.
When run by the service, the script has an error when using various libraries including pygame and pyautogui.
My service is as follows:
[Unit]
Description=My magic service
After=multi-user.target
Requires=network.target
[Service]
Type=simple
User=pi
ExecStart=/usr/bin/python3 /home/pi/FinalCode.py
Restart=always
StandardOutput=file:/tmp/FinalTests.log
StandardError=inherit
[Install]
WantedBy=multi-user.target
The welcome message from pygame prints (Hello from the pygame community... etc), however it the returns the following error:
Traceback (most recent call last):
File "/home/pi/FinalCode.py", line 89, in <module>
for event in pygame.event.get(): # read joystick commands
pygame.error: video system not initialized
I then commented out all the pygame, but a similar issue also occurs with pyautogui, which returns the following error:
Traceback (most recent call last):
import pyautogui
File "/home/pi/.local/lib/python3.9/site-packages/pyautogui/__init__.py", line 249, in <module>
import mouseinfo
File "/home/pi/.local/lib/python3.9/site-packages/mouseinfo/__init__.py", line 223, in <module>
_display = Display(os.environ['DISPLAY'])
File "/usr/lib/python3.9/os.py", line 679, in __getitem__
raise KeyError(key) from None
KeyError: 'DISPLAY'
I have checked "sys.prefix" and "sys.base_prefix" and both in the terminal and from the service they are "/usr" (I think this shows that it is running in the same environment?). Both the service and idle/terminal are running Python 3.9.2 through "/usr/bin/python3"
How do I get the systemd service to run in exactly the same way as the terminal or IDLE running the script?
The basic problem you're running into is that the Systemd unit has no idea where you want this thing displayed. It is missing the DISPLAY environment variable, which is set when Xorg is running but will not be set otherwise.
I think this answer to a similar question might help you out. Long story short - Make your service a user service and change some dependencies and then import the variables from where ever you start Xorg (Login managers have some way of handling this but I only ever really used startx until I switched to wayland and so I have little to offer here).
Found a solution that works, the issue was as bbenne10 suggested.
With hindsight, somewhat unsurprisingly, pyautogui also needs the display so had no issues afterwards.
I am writing a test program which contains the mouse, and keyboard modules together, but they conflict when I run the program.
If applicable, I run Linux Mint 20.04 (Uma).
Here is my code:
import keyboard
import mouse
import time
time.sleep(2)
print("Finished part 1!")
x, y = mouse.get_position()
time.sleep(2)
print("Finished part 2!")
mouse.move(x, y)
time.sleep(2)
print("Finished part 3!")
keyboard.add_hotkey('ctrl+alt+c', mouse.move(x, y))
If I run this program normally, such as /bin/python3 /home/bhrz/Scripts/Python/Mouse/main.py in my terminal, it outputs:
Finished part 1!
Finished part 2!
Finished part 3!
Traceback (most recent call last):
File "/home/bhrz/Scripts/Python/Mouse/main.py", line 18, in <module>
keyboard.add_hotkey('ctrl+alt+c', mouse.move(x, y))
File "/usr/local/lib/python3.8/dist-packages/keyboard/__init__.py", line 639, in add_hotkey
_listener.start_if_necessary()
File "/usr/local/lib/python3.8/dist-packages/keyboard/_generic.py", line 35, in start_if_necessary
self.init()
File "/usr/local/lib/python3.8/dist-packages/keyboard/__init__.py", line 196, in init
_os_keyboard.init()
File "/usr/local/lib/python3.8/dist-packages/keyboard/_nixkeyboard.py", line 113, in init
build_device()
File "/usr/local/lib/python3.8/dist-packages/keyboard/_nixkeyboard.py", line 109, in build_device
ensure_root()
File "/usr/local/lib/python3.8/dist-packages/keyboard/_nixcommon.py", line 174, 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.
When I attempt to solve that error by entering this, sudo /bin/python3 /home/bhrz/Scripts/Python/Mouse/main.py, it outputs:
Traceback (most recent call last):
File "/home/bhrz/Scripts/Python/Mouse/main.py", line 2, in <module>
import mouse
ModuleNotFoundError: No module named 'mouse'
I have looked for answers, and some were to do the above, which as you can see, has resulted in failure, and another said to do sudo su then run the script--which also failed, with the same output as above.
Please help me figure out what the problem is.
I do have unintentionally 3 versions of python installed: 2.7, 3.8.10, and 3.9.5. I personally installed Python 3.9.5. I don't use 2.7, but it was installed with the python-dev
On Python 3.9.5, the keyboard module isn't recognized, but on Python 3.8.10, it is.
I have found the answer to my problem. The thread: Python can't find module when started with sudo 's second answer fixed my problem.
Instead of running sudo python3(/3.8) myScriptName.py, run sudo -E python3(/3.8) myScriptName.py.
Thank you, Nima for attempting to help me!
Use sudo /bin/python3.8 /home/bhrz/Scripts/Python/Mouse/main.py as you said:
On Python 3.9.5, the keyboard module isn't recognized, but on Python 3.8.10, it is.
python3 has been replaced when you installed python3.9.5. So it belongs to python 3.9.5. You need to use python3.8 in order to execute your script in python 3.8.10 environment.
I am writing a simple network scanner with python using scapy following is my code :
import scapy.all as scapy
def scan(ip):
scapy.arping(ip)
scan("192.168.1.1/24")
Error I am getting :
Traceback (most recent call last):
File "ipScanner.py", line 10, in <module>
scan("192.168.1.1/24")
File "ipScanner.py", line 8, in scan
scapy.arping(ip)
File "/Users/omairkhan/opt/anaconda3/lib/python3.7/site-packages/scapy/layers/l2.py", line 648, in arping
filter="arp and arp[7] = 2", timeout=timeout, iface_hint=net, **kargs) # noqa: E501
File "/Users/omairkhan/opt/anaconda3/lib/python3.7/site-packages/scapy/sendrecv.py", line 553, in srp
filter=filter, nofilter=nofilter, type=type)
File "/Users/omairkhan/opt/anaconda3/lib/python3.7/site-packages/scapy/arch/bpf/supersocket.py", line 242, in __init__
super(L2bpfListenSocket, self).__init__(*args, **kwargs)
File "/Users/omairkhan/opt/anaconda3/lib/python3.7/site-packages/scapy/arch/bpf/supersocket.py", line 62, in __init__
(self.ins, self.dev_bpf) = get_dev_bpf()
File "/Users/omairkhan/opt/anaconda3/lib/python3.7/site-packages/scapy/arch/bpf/core.py", line 114, in get_dev_bpf
raise Scapy_Exception("No /dev/bpf handle is available !")
scapy.error.Scapy_Exception: No /dev/bpf handle is available !
Exception ignored in: <function _L2bpfSocket.__del__ at 0x105984c20>
Traceback (most recent call last):
File "/Users/omairkhan/opt/anaconda3/lib/python3.7/site-packages/scapy/arch/bpf/supersocket.py", line 139, in __del__
self.close()
File "/Users/omairkhan/opt/anaconda3/lib/python3.7/site-packages/scapy/arch/bpf/supersocket.py", line 211, in close
if not self.closed and self.ins is not None:
AttributeError: 'L2bpfSocket' object has no attribute 'ins'
Can anyone please help understand it.
NOTE: I am running it on mac OS.
I wrote this exact program when I first started programming with matching syntax, and it ran correctly on my systems when run as administrator. I develop on Linux and Windows rather than Mac, but I will offer what I can.
Are you running this script through your IDE or calling it from the shell?
I recommend only running it from the shell. This simply gives you more control over the files like specifying which version of python the script is, and if you need administrative privileges for a script, you can elevate the script permissions in the shell.
Also, in my OS, I was taught to always use, and have experienced the mistakes of forgetting this, always add:
#!/usr/bin/env python
as the first line of every script. At least in Linux, it tells the PC how to treat the file (it tells it to treat the file as a python file--yes I acknowledge that its already running it as python). I would check to see if that is valid for MacOS file system.
Most of what I have recommended so far comes down to no /dev/bpf handle is available, only ever being an issue for me when I'm not running script as an administrator (although Linux states permission denied). And I shouldn't leave out that using Anaconda on Windows in the past (before I understood the structure of my file systems) prevented me from using common modules like pygame and scapy. I could only guess in that case Anaconda prevented the PC from knowing where to find every piece of that module by making the computer think it had its own one of that module under Anaconda directory when it was in a different PATH.
When I click on my Python IDE's (IDEL, PyScripter) they will not even open. I tried typing python in the command prompt and this is what happened:
C:\>python
Traceback (most recent call last):
File "C:\Python27\ArcGIS10.5\lib\site.py", line 548, in <module>
main()
File "C:\Python27\ArcGIS10.5\lib\site.py", line 537, in main
aliasmbcs()
File "C:\Python27\ArcGIS10.5\lib\site.py", line 469, in aliasmbcs
codecs.lookup(enc)
File "C:\Python27\ArcGIS10.5\lib\encodings\__init__.py", line 85, in search_function
norm_encoding = normalize_encoding(encoding)
File "C:\Python27\ArcGIS10.5\lib\encodings\__init__.py", line 57, in normalize_encoding`enter code here`
encoding = str(encoding, "ascii")
TypeError: str() takes at most 1 argument (2 given)
Did you recently install ArcGIS? It looks to me like ArcGIS installed a few libraries, and overwrote your site.py, but it's using code that's meant for Python3 rather than Python2.7. The str function is capable of taking in 2 arguments in Python3 but not in Python2.
To get your Python to work again, you could try deleting the entire ArcGIS10.5 directory from your computer (or temporarily moving it to your desktop and seeing if that helps). You can also try running python -S in Command Prompt to run Python without importing site.py.
To try to get ArcGIS working, you might be able to install Python3, and reinstall ArcGIS using that.
Hopefully that helps!
So yesterday I updated to Enthought version 1.1 and now it refuses to open. I've rebooted my computer as well as did a re-install of enthought canopy. I keep getting the following error
Traceback (most recent call last):
File "build/bdist.macosx-10.5-i386/egg/canopy/app/bootstrap.py", line 1989, in main
File "build/bdist.macosx-10.5-i386/egg/canopy/app/bootstrap.py", line 1021, in main
File "build/bdist.macosx-10.5-i386/egg/canopy/app/bootstrap.py", line 1012, in _ kill_leftover_procs
File "build/bdist.macosx-10.5-i386/egg/canopy/app/running_process_manager.py", line 116, in kill_leftover_procs
File "/Applications/Canopy.app/appdata/canopy-1.1.0.1371.macosx-x86_64/Canopy.app/Contents/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "build/bdist.macosx-10.5-i386/egg/canopy/app/running_process_manager.py", line 59, in lock
LockError: Lock could not be acquired
I have no idea what's going on here. I've sent the error report to enthought but does anyone have any ideas?
I think I did it. Try searching for these files in your Terminal. They're inside your .canopy folder. Make sure that you're working on your root directory. They're not searchable via Finder. My Canopy's finally working now. Hope this helps.
proc_manager.lock
process.lck
running_procs.pkl
Somehow it seems like a lock file didn't get cleaned in the process. Look into the ~/.canopy folder and remove the process.lck file. You may also start your Activity Monitor and make sure there is no stray canopy or python process, and kill it if there is (or log out of OSX and log back in, which will do the same thing). Canopy will run as normally after that.