Running one function without stopping another

前端 未结 3 1666
北荒
北荒 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:15

    Instead of using raw_input() use this function taken from 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 option

    To make sure that both functions run completely simultaneously you can use this example of threading event:

    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()
    

    In your function you can set an event using event.set(), check it using event.is_set() and clear it using event.clear().

提交回复
热议问题