Issue
I've been trying to make a program that when you press Ctrl+R, it will run another program and kill itself and the other program will start the main program using a subprocess. Popen, the program could not detect the whole key, only Ctrl was detected when I was using keyboard.read_key()
def _restart():
while keyboard.read_key()!="^R":
pass
subpro.Popen([r"C:\Users\Name\AppData\Local\Programs\Python\Python312\python.exe","restarter.py"])
leave()
Solution
Instead of using keyboard.read_key(), you can use a keyboard hook that listens for key events. This will allow you to detect combined keypresses like Ctrl+R.
example code:
import keyboard
import subprocess
import os
import signal
import time
def restart_program():
# Terminate the current program
os.kill(os.getpid(), signal.SIGTERM)
# Start the restarter script
subprocess.Popen([r"C:\Users\Name\AppData\Local\Programs\Python\Python312\python.exe", "restarter.py"])
def on_key_event(event):
if event.name == 'r' and event.event_type == 'down' and keyboard.is_pressed('ctrl'):
restart_program()
# Hook the keyboard events
keyboard.hook(on_key_event)
# Keep the program running
while True:
time.sleep(1)
Answered By - Yokozuna
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.