1

I am writing a reminder program that will send a notification to the user once the time is up and I want the user to be able to quit the notification by pressing a key. I tried the KeyboardInterrupt function but I wanted to use a simple character instead of CTRL + C so I used the keyboard.is_pressed function

import time
import plyer 
import keyboard



reminder = input("What would you like to set a reminder for? ")

while True:

    mode = str(input("For how long? Type s for seconds, m for minutes, or h for hours: "))
    if mode == 's':
        local_time = float(input("In how many seconds? "))
        break
    elif mode == 'm':
        local_time = float(input("In how many minutes? "))
        local_time *= 60
        break
    elif mode == 'h':
        local_time = float(input("In how many hours? "))
        local_time *= 3600
        break
    else:
        print("Invalid input, please try again.")

time.sleep(local_time)

def notfiy():
    while True:
        plyer.notification.notify(title = "Time's Up", message = reminder, timeout = 3)
        if keyboard.is_pressed("q"):
            break
        else:
            break

Without the keyboard interruption, the notification would keep popping up unless I restart the program because of the while true statement. Now that I try to run the program with the keyboard.is_pressed function, the notification doesn't pop up anymore

drum
  • 5,416
  • 7
  • 57
  • 91

2 Answers2

1

use sys.exit() function to terminate a running python program. https://www.askpython.com/python/examples/exit-a-python-program

0

the function notfiy() is never called. I fixed it and also imported sys for exiting the program.

Here is the working code:

import plyer 
import keyboard
import sys
import time

quitit = False
reminder = input("What would you like to set a reminder for? ")

def notfiy(): 
  global quitit 
  time.sleep(local_time)
  timeduration = time.time()  
  while True:
    plyer.notification.notify(title="Time's Up", message=reminder, timeout=3)
    time.sleep(1)
    if quitit or time.time() - timeduration > 10:
      break    
    if keyboard.is_pressed('q'):
      quitit = True    
  sys.exit()

while True: 
  mode = str(input("For how long? Type s for seconds, m for minutes, or h for hours: ")) 
  if mode == 's': 
    local_time = float(input("In how many seconds? ")) 
    notfiy()
  elif mode == 'm': 
    local_time = float(input("In how many minutes? ")) 
    local_time *= 60 
    notfiy()
  elif mode == 'h': 
    local_time = float(input("In how many hours? ")) 
    local_time *= 3600 
    notfiy() 
  else: 
    print("Invalid input, please try again.")
    continue
  break