python怎么监听监控键盘?

请问下,linux下,python如何监听键盘呢?

比如在一个无限循环while结构中,按enter键暂停循环,再按enter键可以继续运行。

阅读 1.4k
1 个回答

主线程另起一个线程监听键盘就可以了。然后通过控制一个标识位来控制任务是否执行。

import time
from concurrent.futures.thread import ThreadPoolExecutor

stop = False


def watch_dog():
    global stop
    while True:
        input()
        stop = not stop


tpe = ThreadPoolExecutor(1, 'watch-enter-')
tpe.submit(watch_dog)

while True:
    if stop:
        print('暂停中...')
        time.sleep(1)
        continue
    print('处理任务中...')
    time.sleep(1)

本文参与了SegmentFault 思否面试闯关挑战赛,欢迎正在阅读的你也加入。
推荐问题