Dani_K
Dani_K

Reputation: 43

How to open a program using keyboard input?

My project is to make a program that you can run while you are playing games or other programs in the background. When you press a certain key, your notepad should open and also close after you press the same key again.

I have managed to open notepad with subprocess and that works fine but I have no idea to make it open only when a certain key is pressed. Thanks for any help!

EDIT: What I tried already:

import subprocess
import keyboard

if keyboard.is_pressed('k'):
    subprocess.Popen('C:\\Windows\\System32\\notepad.exe')

input()

here it just doesn't detect any keyboard input, the input() at the end makes the program not close instantly

import subprocess
import keyboard

keyboard.add_hotkey('ctrl+k', print,args=("hello", "test"))

input()

Here if I press "ctrl+k it" will print hello test that means the hotkey works fine. When I switch this part "print,args=("hello", "test")" to "subprocess.Popen('C:\Windows\System32\notepad.exe')"(it should open the program instead of printing hello test) the notepad opens instantly after I run the program and when I press "ctrl+k" I get a big error.

Upvotes: 0

Views: 1102

Answers (2)

valcarcexyz
valcarcexyz

Reputation: 622

A more complex, but still working example could be the following. With this code your program will be always listening the keyboard, not only when you are focused on the input, so may be mre practical in your case

from pynput import keyboard
import subprocess
import threading

class MyException(Exception): pass

class Listening:
    """Is allways waiting for the keyboard input"""
    def __init__(self):
        self.notepad_open = False # to know the state
        with keyboard.Listener(
                on_press=self.on_press) as listener:
            try:
                listener.join()
            except:
                pass
    
    def on_press(self, key):
        try:
            if key.char == "k":
                if not self.notepad_open:
                    self.subprocess = \
                        subprocess.Popen('C:\\Windows\\System32\\notepad.exe')
                    self.notepad_open = True # update state
                else:
                    self.subprocess.kill()
                    self.notepad_open = False # update state
        except: # special key was pressed
            pass

thread = threading.Thread(target=lambda: Listening())
thread.start()

Upvotes: 1

user13961569
user13961569

Reputation:

The problem is that you check for the key 'k' only once at the beginning. If you want the program to correctly work then you should try this:

import time
import subprocess
import keyboard
while True:
    if keyboard.is_pressed('k'):
        subprocess.Popen('C:\\Windows\\System32\\notepad.exe')
        time.sleep(5)

-I used the time so that you can only open the program once 5 seconds(If you're curious, see what happens without it)-

Upvotes: 1

Related Questions