python - 在Python中的独立(非阻塞)线程中检测按键

标签 python multithreading python-3.x

在Python脚本中,我想连续调用一个函数,同时监听用户按下ESC键,然后退出程序。

这是我当前的代码:

import threading
import msvcrt

def wait_for_esc():
  while True:
    key = ord(msvcrt.getch())
    if key == 27:
      print("ESC")
      exit(0)

def do_something():
  while True:
    call_function()

thread_1 = threading.Thread(name="wait_for_esc", target=wait_for_esc())
thread_2 = threading.Thread(name="do_something", target=do_something())

thread_1.start()
thread_2.start()

但是,似乎 thread_1 会阻塞 thread_2,直到按下任意键为止。

使两个线程彼此独立运行的可能解决方案是什么?

最佳答案

当你将目标任务传递给线程时,你需要传递函数对象——而不是调用函数。您需要删除函数名称末尾的括号。

thread_1 = threading.Thread(name="wait_for_esc", target=wait_for_esc)
thread_2 = threading.Thread(name="do_something", target=do_something)

它应该可以工作。

关于python - 在Python中的独立(非阻塞)线程中检测按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47793417/

相关文章:

java - Akka future 指导

python - 词频分析-TypeError : '>=' not supported between instances of 'list' and 'int'

python - 如何将纯 http 请求发送到 url?

python - 为什么 python 假设我的路径是项目根目录,这是两个目录级别?

python - GPyOpt 的 "First Step"示例应该找到最小值吗?

java - 内联 Thread 对象的运行速度比从 Thread 继承的类快得多

python - 如何在networkx中的网格上绘制节点图

c# - 使用 PLINQ Extensions 时,线程标识是否被转移?

python - pip -e : No magic underscore to dash replacement

python - 在 django 自定义模型管理添加页面处理自定义提交按钮的正确方法