make python script run for a minute

  • A+
Category:Languages

I'm working on a small project where the script is to monitor user's keyboard inputs and I only want the script to run for a duration of 1 minute. After that minute has passed, I was a final print statement of the inputs and to terminate the script. The time.sleep function is not a viable choice here since I want to update variables and receive output every action and using sleep will only delay each input.

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

 


This will be the answer:

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: