简体   繁体   中英

How can i detect CTRL+C in python3.8?

I have this program in pycharm python3.8 that i need to detect if ctrl+c is pressed anywhere while browsing windows while the program is running, but for some reason the program does not detect if the pressed key is the "ctrl" my code looks like this:

from pynput import keyboard

def on_press(key):
    if any([key in COMBO for COMBO in COMBINATIONS]):
        current.add(key)
        if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):
            print("Ctrl+C pressed")

def on_release(key):
    if any([key in COMBO for COMBO in COMBINATIONS]):
        current.remove(key)

COMBINATIONS = [
    {keyboard.Key.ctrl, keyboard.KeyCode(char='c')}
]

current = set()

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

It never gets to print the message. I am running the program on Windows 10 Pycharm internal command line

Thanks!

Try this code:

try:
    while True: ### YOUR CODDE
        pass    ### 
except KeyboardInterrupt:
    print('You pressed ctrl+c')

Without any library and fastest method

To see what's happening, add a line to the top of on_press that shows each keypress:

def on_pres(key):
   print(key,)
   # ...

When you press ^C , you'll notice you get \x03 ... This is one of the ASCII control characters . Most of them aren't really used that much these days, but this was originally the whole point of the control key. :D

It looks like in pynput, you can catch ^C by testing against chr(ord("C")-64) ... And the same for all the other control characters.

(BTW, Thanks for telling us about pynput. So much easier than what I used in the past!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM