代码之家  ›  专栏  ›  技术社区  ›  mike-gallego

让python脚本运行一分钟

  •  2
  • mike-gallego  · 技术社区  · 6 年前

    我正在做一个小项目,其中的脚本是监测用户的键盘输入,我只希望脚本运行1分钟。在那一分钟过后,我想要输入的最终打印语句并终止脚本。在这里,time.sleep函数不是一个可行的选择,因为我想更新变量并接收每个操作的输出,而使用sleep只会延迟每个输入。

    from pynput import keyboard
    
    word_counter = 0
    
    
    def on_press(key):
        global word_counter
        try:
            print('alphabet key {} pressed'.format(key.char))
        except AttributeError:
            if key == keyboard.Key.space:
                word_counter += 1
                print(word_counter)
            elif key == keyboard.Key.esc:
                return False
            print('special key {} pressed'.format(key))
    
    
    with keyboard.Listener(on_press=on_press) as listener:
        listener.join()
    
    # After a minute, this will be the final output and the program will terminate
    print('You typed a total of {} words in a minute'.format(word_counter))
    
    2 回复  |  直到 6 年前
        1
  •  5
  •   Hoseong Jeon    6 年前

    这就是答案:

    from pynput import keyboard
    import threading, time
    
    word_counter = 0
    
    def background():
        def on_press(key):
            global word_counter
            try:
                print('alphabet key {} pressed'.format(key.char))
            except AttributeError:
                if key == keyboard.Key.space:
                    word_counter += 1
                    print(word_counter)
                elif key == keyboard.Key.esc:
                    return False
                print('special key {} pressed'.format(key))
    
        with keyboard.Listener(on_press=on_press) as listener:
            listener.join()
    
    def wait():
        time.sleep(60)
    
    background = threading.Thread(name = 'background', target = background)
    background.start()
    wait()
    
    # After a minute, this will be the final output and the program will terminate
    print('You typed a total of {} words in a minute'.format(word_counter))
    
        2
  •  1
  •   Nithish Albin    6 年前
    from pynput import keyboard
    import time
    
    word_counter = 0
    
    
    def on_press(key):
        global word_counter
        try:
            print('alphabet key {} pressed'.format(key.char))
        except AttributeError:
            if key == keyboard.Key.space:
                word_counter += 1
                print(word_counter)
            elif key == keyboard.Key.esc:
                return False
            print('special key {} pressed'.format(key))
    i=int(time.time())+60
    while(time.time()<=i):
         with keyboard.Listener(on_press=on_press) as listener:
              listener.join()
    
    # After a minute, this will be the final output and the program will terminate
    print('You typed a total of {} words in a minute'.format(word_counter))
    

    我相信这段代码会运行1分钟。

    如:

    import time 
    
    i=int(time.time())+60
    print("ddnd")
    while(int(time.time())<=i):
        print("dlksnd")