代码之家  ›  专栏  ›  技术社区  ›  Gerald Artefacto

如何在python中等待输入而不阻塞计时器?

  •  2
  • Gerald Artefacto  · 技术社区  · 10 年前

    我需要每x秒打印一条消息, 同时 ,我需要倾听用户的输入。如果按下“q”,应该会终止程序。

    例如

    some message
    .
    . # after specified interval
    . 
    some message
    q # program should end
    

    我现在面临的问题是 raw_input 正在阻止,这将阻止my函数重复消息。如何使输入读数和函数并行运行?

    编辑:事实证明 原始输入 未阻止。我误解了多线程的工作原理。我会把这个留在这里,以防有人碰到它。

    2 回复  |  直到 10 年前
        1
  •  4
  •   DorElias    10 年前

    您可以使用线程在不同的线程中打印消息。

    import threading
    
    t = threading.Timer(30,func,args=[])
    t.start()
    

    其中30是调用func的频率。

    func是在不同线程中调用的函数。

    args是用于调用函数的参数数组

    如果您只想调用一个不同的函数,您可以这样做

    t = threading. Thread(target=func, args=[]) 
    t.start() 
    

    这将使func并行运行

        2
  •  2
  •   Anvesh Arrabochu    10 年前
    import threading
    import time as t
    
    value = 0
    
    def takeInput():
        """This function will be executed via thread"""
        global value
        while True:
            value = raw_input("Enter value: ")
            if value == 'q':
                exit()  # kills thread
            print value
        return
    
    if __name__ == '__main__':
        x = int(raw_input('time interval: '))
        thread = threading.Thread(target=takeInput)
        thread.start()
        while True:
            if value == 'q':
                exit()  # kills program
            print 'some message'
            t.sleep(x)