Running one function without stopping another

前端 未结 3 1706
北荒
北荒 2021-01-20 03:55

How can I run a timer while asking for user input from the console? I was reading about multiprocessing, and I tried to use this answer: Python: Executing multiple functions

3条回答
  •  日久生厌
    2021-01-20 04:21

    Only addressing your concerns, here is a quick fix using threading :

    import time
    import sys  
    import os 
    
    def start_timer():
      global timer
      timer = 10 
      while timer > 0:
        time.sleep(1)
        timer -= 1
        sys.stdout.write ("There's only %i seconds left. Good luck. \r" % (timer))
        sys.stdout.flush()
        #cut_wire() ==> separate call is easier to handle
      if timer == 0:
      print("Boom!")
      os._exit(0)    #sys.exit() only exits thread
    
    def cut_wire():
      wire_choice = raw_input("\n> ")
      if wire_choice == "cut wire" or wire_choice == "Cut Wire":
        stop_timer()
      else:
        print("Boom!")
        os._exit(0)    #same reason
    
    if __name__ == '__main__':
      import threading
      looper = threading.Thread(target=start_timer)
      looper.start()
      cut_wire()
    

提交回复
热议问题