Python事件循环多线程处理如何同时运行两位代码?

2024-05-08 14:44:56 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试图利用msvcrt.getch()在程序中的任何地方选择退出(不使用键盘中断)。在

我的代码当前如下所示:

导入msvcrt 导入系统

打印(“随时按q退出”)

while True:
    pressedKey = msvcrt.getch()
    if pressedKey == 'q':    
       sys.exit()
    else:
       # do some setup
       if myvar == "string":
           try:
               # do stuff
           except:
               # do stuff 
       else:
           #do stuff

我如何运行while循环来检测在运行其他块(即# do stuff块)的同时按下q的键?在

这样,如果用户继续执行该程序,那么它只会运行一次。但是如果他们点击q,程序就会退出。在


Tags: 代码程序true利用if系统地方键盘
1条回答
网友
1楼 · 发布于 2024-05-08 14:44:56

您可以在单独的线程或(更好)use ^{} as @martineau suggested中读取密钥:

#!/usr/bin/env python
import msvcrt
from Queue import Empty, Queue
from threading import Thread

def read_keys(queue):
    for key in iter(msvcrt.getch, 'q'): # until `q`
        queue.put(key)
    queue.put(None) # signal the end

q = Queue()
t = Thread(target=read_keys, args=[q])
t.daemon = True # die if the program exits
t.start()

while True:
    try:
        key = q.get_nowait() # doesn't block
    except Empty:
        key = Empty
    else:
        if key is None: # end
            break
    # do stuff

If I wanted to do something in the main code when the second thread detected a certain keypress, how would I act on that?

在代码再次到达q.get_nowait()之前,您不会对主线程中的按键做出反应,也就是说,在“do stuff”完成循环的当前迭代之前,您不会注意到按键。如果您需要做一些可能需要很长时间的事情,那么您可能需要在另一个线程中运行它(启动新线程或使用线程池,如果在某个时刻阻塞是可以接受的)。在

相关问题 更多 >