代码之家  ›  专栏  ›  技术社区  ›  Robert Strauch

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

  •  1
  • Robert Strauch  · 技术社区  · 8 年前

    在Python脚本中,我想连续调用一个函数,同时监听用户按下 电子稳定控制系统 然后退出程序的键。

    这是我当前的代码:

    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 直到按下任何键。

    有什么可能的解决方案可以独立运行两个线程?

    1 回复  |  直到 8 年前
        1
  •  2
  •   Chen A.    8 年前

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

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

    它应该会起作用。