简体   繁体   English

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

[英]Python event loop — multithreading — How to run two bits of code simultaneously?

So I'm trying to utilize msvcrt.getch() to make an option to quit(without using KeyBoardInterrupt) anywhere in the program. 因此,我试图利用msvcrt.getch()在程序中的任何位置做出退出(不使用KeyBoardInterrupt的选项msvcrt.getch()的选项。

My code currently looks like this: 我的代码当前如下所示:

import msvcrt import sys 导入msvcrt导入sys

print("Press q at any time to quit") 打印(“随时按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

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)? 如何在运行另一个循环的同时运行while循环以检测q的按键( # do stuff块)?

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. 但是,如果他们按q ,则程序将退出。

You could read keys in a separate thread or (better) use msvcrt.kbhit() as @martineau suggested : 您可以在单独的线程中读取键,也可以(最好) 使用msvcrt.kbhit()如@martineau建议的那样

#!/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? 如果我想在第二个线程检测到某个按键时在主代码中执行某项操作,该如何处理?

You do not react to the key press in the main thread until code reaches q.get_nowait() again ie, you won't notice the key press until "do stuff" finishes the current iteration of the loop. 在代码再次到达q.get_nowait()之前,您不会对主线程中的按键作出反应,即,直到“ do stuff”完成循环的当前迭代之前,您不会注意到按键。 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). 如果您需要执行可能需要很长时间的操作,则可能需要在另一个线程中运行它(如果可以接受某个时刻的阻塞,则可以启动新线程或使用线程池)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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