运行一个功能而不停止另一个

时间:2015-10-10 22:01:50

标签: python function

如何在从控制台请求用户输入时运行计时器?我正在阅读有关多处理的内容,我尝试使用这个答案:Python: Executing multiple functions simultaneously。当我试图让它继续下去时,它给了我一堆框架错误。

现在它运行start_timer(),但在运行cut_wire()时停止它。

这是我的start_timer功能:

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()
    if timer == 0:
        print("Boom!")
        sys.exit()

这是cut_wire函数:

def cut_wire():
    wire_choice = raw_input("\n> ")
    if wire_choice == "cut wire" or wire_choice == "Cut Wire":
        stop_timer()
    else:
        print("Boom!")
        sys.exit()

3 个答案:

答案 0 :(得分:1)

当然它在播放cut_wire函数时停止运行,因为“raw_input”命令读取文本并等待用户放置文本并按回车键。

我的建议是检查他们按键是否按“Enter”,然后当按键时,请读取该行。如果没有按键,请继续使用计时器。

问候。

答案 1 :(得分:1)

而不是使用raw_input()使用此功能取自here

def readInput( caption, timeout = 1):
start_time = time.time()
sys.stdout.write('\n%s:'%(caption));
input = ''
while True:
    if msvcrt.kbhit():
        chr = msvcrt.getche()
        if ord(chr) == 13: # enter_key
            break
        elif ord(chr) >= 32: #space_char
            input += chr
    if len(input) == 0 and (time.time() - start_time) > timeout:
        break

print ''  # needed to move to next line
if len(input) > 0:
    return input
else:
    return ""

Thearding选项

要确保两个函数完全同时运行,您可以使用此线程事件示例:

import threading
event = threading.Event()
th = theading.Thread(target=start_timer, args=(event, ))
th1 = theading.Thread(target=cut_wire, args=(event, ))
th.start()
th1.start()
th.join()
th1.join()

在您的功能中,您可以使用event.set()设置活动,使用event.is_set()进行检查并使用event.clear()进行清除。

答案 2 :(得分:1)

仅解决您的疑虑,以下是使用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()
相关问题