UnboundLocalError: local variable 'toggled' referenced before assignment - python

I was working on a random python script but I've encountered the above error and cannot figure out how to work it out.
Code:
from pynput.keyboard import Key, Controller, Listener
import time
keyboard = Controller
key = "e"
toggle = Key.f6
toggled = False
def on_press(key):
print(f"on_press() triggered, key = {key}")
if key == toggle:
toggled = not toggled
def on_release(key):
print(f"on_release() triggered, key = {key}")
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
while True:
if toggled:
keyboard.press(key)
time.sleep(3)
keyboard.release(key)
time.sleep(1)

Related

How to pause a pynput event listener

I am trying to make a program that will read the user's inputs and if it detects a certain key combination, it will type a special character. Currently I am testing and I want the script to just output a '+' after each character that the user types. I am using the pynput event listener to determine if a key was pressed and using a 'Pause' variable so that the output of the '+' doesn't cause the event listener to make an infinite loop. The problem is that the event listener is going into an infinite loop anyway and I am not sure why.
Current typed output after each key press: +++++++++++++++++++...
Desired typed output after each key press: +
Current console output after each key press:
pause is False
getting pressed
getting released
['f']
paused
send outputs
unpaused
pause is False
getting pressed
getting released
['+']
paused
send outputs
unpaused
pause is False
getting pressed
getting released
['+']
paused
send outputs
unpaused
pause is False
getting pressed
getting released
...
Desired console output after each key press:
pause is False
getting pressed
getting released
['f']
paused
send outputs
pause is True
unpaused
import pynput
import time
from pynput.keyboard import Key, Listener, Controller
keyboardOut = Controller()
PressedKeys = []
ReleasedKeys = []
Pause = False
def on_press(key):
global PressedKeys, ReleasedKeys, Pause
print("pause is "+str(Pause))
if Pause == False:
print("getting pressed")
PressedKeys.append(key)
else:
return
def on_release(key):
global PressedKeys, ReleasedKeys, Pause
if Pause == False and len(PressedKeys) > 0:
print("getting released")
ReleasedKeys.append(key)
test_frame()
else:
return
def test_frame():
global Pause
print(PressedKeys)
Pause = True
print("paused")
print("send outputs")
keyboardOut.press('+')
keyboardOut.release('+')
PressedKeys.clear()
ReleasedKeys.clear()
Pause = False
print("unpaused")
time.sleep(1)
# Collect events until released
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
How can I fix my code to *actually* pause the event listener. I am new to python, so I might just not understand how to update global variables correctly.
You have to stop the listener before using the keyboard controller.
I hope this code helps out, I tried to get as close to what I thought you were looking for.
code:
from pynput import keyboard
from time import sleep
KeyboardOut = keyboard.Controller()
pressed_keys = []
released_keys = []
def on_press(key):
try:
pressed_keys.append(format(key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
if len(pressed_keys) > 0:
released_keys.append(format(key))
test_frame()
return False
if key == keyboard.Key.esc:
# Stop listener
return False
def test_frame():
print('\n\n'+str(pressed_keys))
print('paused')
print('send outputs')
KeyboardOut.press('+')
KeyboardOut.release('+')
pressed_keys.clear()
released_keys.clear()
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.run()
print('unpaused')
sleep(1)
return True
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.run()

Detect press of alt key with pynput keyboard

I am trying to hold down the alt key when I press it with pynput. I checked the documentation and could not find a list saying how to call all specific keys or detect all specific keys. So that sucks.
I've used their cookie-cutter code for detecting presses to try and detect keys:
from pynput.keyboard import Key, Listener
def on_press(key):
print('{0} pressed'.format(
key))
def on_release(key):
print('{0} release'.format(
key))
if key == Key.esc:
# Stop listener
return False
# Collect events until released
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
but when I try to modify it like this...
from pynput import keyboard
def on_press(key):
try:
print('Alphanumeric key pressed: {0} '.format(
key.char))
except AttributeError:
print('special key pressed: {0}'.format(
key))
def on_release(key):
print('Key released: {0}'.format(
key))
if key == keyboard.Key.alt_1: <------ this
print('test')
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
It just quits when I attempt to press alt or any key I select for the if statement.
Ideally, I'd like to do this:
from pynput import keyboard
def on_release(key):
if key == keyboard.Key.alt_1:
keyboard.press.alt_1
# Collect events until released
with keyboard.Listener(on_release=on_release) as listener:
listener.join()
but obviously, I can't even reach this point. Help?
I don't understand why you use alt_1 instead of alt.
And if you want to send some key then you have to use Controller()
This code works for me
from pynput.keyboard import Key, Listener, Controller
def on_press(key):
print(f'{key} pressed')
def on_release(key):
print(f'{key} released')
if key == Key.alt:
print('>>> I press ALT <<<')
controller.press(Key.alt)
if key == Key.esc:
# Stop listener
return False
#--- main ---
controller = Controller()
# Collect events until released
with Listener(on_press=on_press,on_release=on_release) as listener:
# ... other code ...
listener.join()

Is it possible to press the key without running the if statement again

I'm trying to replace volume media keys with media next-prev keys. The problem is the key volume down or up gets pressed.
from pynput.keyboard import Key, Listener, Controller
keyboard = Controller()
def on_press(key):
if key == Key.media_volume_up:
keyboard.press(Key.media_down)
keyboard.press(Key.media_next)
if key == Key.media_volume_down:
keyboard.press(Key.media_volume_up)
keyboard.press(Key.media_previous)
def on_release(key):
pass
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
I tried to make it like this but it also triggers the previous if statement so it's looping.
from pynput.keyboard import Key, Listener, Controller
keyboard = Controller()
block = False
def on_press(key):
global block
if not block:
if key == Key.media_volume_up:
block = True
keyboard.press(Key.media_volume_down)
keyboard.press(Key.media_next)
block = False
if key == Key.media_volume_down:
block = True
keyboard.press(Key.media_volume_up)
keyboard.press(Key.media_previous)
block = False
def on_release(key):
pass
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()

How to see what character is pressed with pynput python 3.7?

How can you see which button is pressed in pynput.
from pynput.keyboard import Key, Listener
def a(key):
print('{0} pressed'.format(
key))
if key == 'a':
print('ape')
with Listener(on_press = a) as listener:
listener.join()
Does not see work.
from pynput.keyboard import Listener
def a(key):
print(f"{key}, was pressed")
if key.char == "a":
print("foo")
with Listener(on_press=a) as listener:
listener.join()
Output:
q'q', was pressed
w'w', was pressed
a'a', was pressed
foo
s's', was pressed
However this will cause issues if you press the caps lock for example so I would place in a try except block:
try:
if key.char == 'a':
print("foo")
except AttributeError:
pass

Keyboard Listener from pynput

I am trying to import a keyboard listener into my class but keep getting a
NameError: name 'on_press' is not defined
Here is my code:
from pynput import keyboard
class game_code:
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
def check_key_press(self,key):
try: k = key.char
except: k = key.name
if k in ['up', 'down', 'left', 'right']:
self.key = keys.append(k)
return True
else:
return False
Also not 100% sure on how with statements work.
I got it working using the format of their documentation online:
https://pythonhosted.org/pynput/keyboard.html
from pynput.keyboard import Key, Listener
def on_press(key):
#print('{0} pressed'.format(
#key))
check_key(key)
def on_release(key):
#print('{0} release'.format(
# key))
if key == Key.esc:
# Stop listener
return False
def check_key(key):
if key in [Key.up, Key.down, Key.left, Key.right]:
print('YES')
# Collect events until released
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()

Categories