簡體   English   中英

在程序運行時按下任意鍵時停止 python 程序

[英]Stopping a python program when an arbitrary key was pressed while the program is running

我最近了解了 python 模塊信號。 有了它,我們可以捕獲一個 SIGINT 並在捕獲它之后做我們想做的事情。 我使用它如下。 在那種情況下,我只是使用 SIGINT 來打印該程序將被停止並停止該程序。

import signal  
import os
import time

def signalHandler(signalnumb, frame):  
    print("Signal Number:", signalnumb, " Frame: ", frame)
    print('Exiting the program...')
    os._exit(0)
 
signal.signal(signal.SIGINT, signalHandler)
 
c=0
# Loop infinite times using the while(1) which is always true
while 1:
    print(c)
    #sleep for 1 seconds using the sleep() function in time 
    time.sleep(1)
    c=c+1

現在我想從鍵盤發出任何信號(例如按“q”),一旦收到信號,python 程序就應該停止。 有沒有人有一些經驗如何做到這一點? 接受任何其他方法而不是使用信號模塊(例如使用多線程)。

Edit1- 后來我嘗試使用類似問題之一中建議的 pynput 模塊。 我肯定做錯了。 它不像我預期的那樣工作。 這意味着通過按鍵,我無法停止 for 循環的運行。

from pynput import keyboard
import time

def on_press(key):
    for i in range(100):
        print(i)
        time.sleep(1)
        if key == keyboard.Key.esc:
            return False  # stop listener
        try:
            k = key.char  # single-char keys
        except:
            k = key.name  # other keys
        if k in ['1', '2', 'left', 'right']:  # keys of interest
            # self.keys.append(k)  # store it in global-like variable
            print('Key pressed: ' + k)
            return False  # stop listener; remove this if want more keys

listener = keyboard.Listener(on_press=on_press)
listener.start()  # start to listen on a separate thread
listener.join()  # remove if main thread is polling self.keyspython

有人可以指出如何以正確的方式使用 pynput 嗎?

這是我最初的實現:

a = input('Press a key to exit')
if a:
    exit(0)

但是,您似乎需要一段代碼來允許單擊任何鍵並立即退出程序,而無需隨后按 Enter。 這可能是一個更好的方法:

import readchar
print("Press Any Key To Exit")
k = readchar.readchar()

希望這可以幫助!

在仔細了解線程和 pynput 模塊后,我設法使用按鍵回調停止了 for 循環(或任何作為單獨線程運行的程序)。

from pynput import keyboard
import os
import threading
import time

loop_running = False

def on_press(key):
    print(dir(key))
    global loop_running
    #if key == keyboard.Key.delete and not loop_running:
    if ('char' in dir(key)) and (key.char == 's') and (not loop_running):
        t=threading.Thread(target=start_loop)
        t.start()
        
    #elif key==keyboard.Key.tab:   #if this is used, the attributes related to 'key' will be changed. you can see them since I have used a print(dir(key))
    elif key.char == 'q':
        loop_running=False
        

def start_loop():
    global loop_running
    loop_running = True
    for i in range(100):
        if not loop_running:
            os._exit(0)                          
            
        print(i)
        time.sleep(1)
        
with keyboard.Listener(on_press=on_press) as listner:
    listner.join()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM