Python事件循环-多线程-如何同时运行两位代码? [英] Python event loop -- multithreading -- How to run two bits of code simultaneously?

查看:211
本文介绍了Python事件循环-多线程-如何同时运行两位代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图利用msvcrt.getch()在程序中的任何位置做出退出(不使用KeyBoardInterrupt的选项)的选项.

So I'm trying to utilize msvcrt.getch() to make an option to quit(without using KeyBoardInterrupt) anywhere in the program.

我的代码当前如下所示:

My code currently looks like this:

导入msvcrt 导入系统

import msvcrt import sys

打印(随时按q退出")

print("Press q at any time to quit")

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

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

How do I run the while loop to detect the keypress of q at the same time as I'm running the other (the # do stuff blocks)?

这样,如果用户继续使用该程序,他们将只运行一次.但是,如果他们按 q ,则该程序将退出.

That way, if the user goes ahead with the program, they it'll only run it once. But if they hit q, then the program will quit.

推荐答案

您可以在单独的线程中读取密钥,也可以(更好)使用使用msvcrt.kbhit()如@martineau建议:

You could read keys in a separate thread or (better) use msvcrt.kbhit() 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"完成循环的当前迭代之前,您不会注意到按键.如果您需要执行可能需要很长时间的操作,则可能需要在另一个线程中运行它(如果可以接受某个时刻的阻塞,则可以启动新线程或使用线程池).

You do not react to the key press in the main thread until code reaches q.get_nowait() again i.e., you won't notice the key press until "do stuff" finishes the current iteration of the loop. If you need to do something that may take a long time then you might need to run it in yet another thread (start new thread or use a thread pool if blocking at some point is acceptable).

这篇关于Python事件循环-多线程-如何同时运行两位代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆