Wednesday, June 1, 2022

[SOLVED] How do you press a specific key to do something in python?

Issue

I want to know to press a specific key to do something in python and no, not the keyboard library it requires root permissions. I could just do sudo /bin/python3.7 "path of python file" but that's gonna be a pain. by the way here's my python code:

import keyboard
import pyautogui as auto
import time

auto.hotkey('alt', 'F2')
auto.write('mousepad')
time.sleep(int(1))
auto.write('do you want to start game?')

keyboard.wait('y')

Solution

from pynput.keyboard import *
import pyautogui as auto
import time

auto.hotkey('alt', 'F2')
time.sleep(int(1))
auto.write('mousepad')
time.sleep(int(1))
auto.write('do you want to start game?')

if key == Key.y:
    # Stop listener
    return False

def on_press(key):
    doing_something_here()


with Listener(
        on_press=on_press,
        on_release=None) as listener:
    listener.join()


Answered By - Anthony Arnzen
Answer Checked By - Marilyn (WPSolving Volunteer)