![]() |
Help adding a loop inside a loop - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Help adding a loop inside a loop (/thread-38413.html) |
Help adding a loop inside a loop - Extra - Oct-09-2022 Hello, I have my virtual assistant's code which is in a while true loop & runs fine, but I want to add a loop inside my virtual assistant's while loop for my checkForReminders() function which scans through an sqlite table to see if any set reminders match the current date and time (if they do a popup opens and if not it should keep scanning until it finds a matching reminder). Is there any way to do this successfully? Thanks in advance. checkForReminders.py def checkForReminders(): #Connect to the database connection = sqlite3.connect(MainDatabase) cursor = connection.cursor() #Get Reminders where their dates & times match today's date & time cursor.execute("SELECT Reminder FROM Reminders WHERE Date = ? AND Time = ?",(currentdate, currentTime)) Results = cursor.fetchall() connection.commit() connection.close() if (Results == []): return else: reminderPopup(Results)My Virtual Assistants Code: #!/usr/bin/env python3 #------------------------------------------------------------------------------------- # B.A.X.T.E.R A.I System #------------------------------------------------------------------------------------- #----------------------------------------------- #B.A.X.T.E.R #Version 5 -> Keyboard Input #Last Updated: 09/04/22 #Developed by Paglia Industries #----------------------------------------------- #---------------------------------------------------------------------------------------------- # Table Of Contents/Overview #---------------------------------------------------------------------------------------------- # Imports # Commander & A.I Name # WishMe Function # Main # - General Conversation, Jokes, & Fun Facts # -- Search Wikipedia # --- Search Wolfram Alpha # ---- Open Stuff on Internet # ----- Open Stuff on Computer # ------ Set Reminders & Renewals # ------- Set ToDo # -------- Send E-mails # --------- Stop Program # Run Program #---------------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------------- # TODO #---------------------------------------------------------------------------------------------- # (1) # Add More Convo Abilities # Iterate through pairs.py to do general convo and fix it's output to match the standard format # Memory Capabilities via Info stored/retrieved in a SQL Database # Open CV & Guesture Controls? # (2) # Setup GUI that takes in Constants (User's Name, DOB, E-Mail, Ect..) & Stores them in Constants.db # (3) # Track packages with Baxter - put tracking # in database and have Baxter check on it when updated # Track prices of items and sends an Email when the price drops # (4) # Access to BAXTER via discord or Email. # Ex: https://realpython.com/how-to-make-a-discord-bot-python/ # (5) # Renewals & Renewal Reminders via Email, or msg Service Like Discord & Popup msgBox via PyQT # (6) # Implement Google/Custom Calendar, so user can add appointments, b-days, events, ect.. # & Have alerts display/popup when events are coming up (1 day & 2-3h before hand) # Ex: https://pypi.org/project/gcalcli/ # (7) # Allow user to better set reminders (pick day, time & repeat times) #---------------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- # Imports #------------------------------------------------------------------------------------- import json import random import datetime import operator import os import subprocess import time import sys from unittest import result import webbrowser import requests from bs4 import BeautifulSoup import wikipedia import wolframalpha from BX_Intents import (greetings, farewell, thanks, noAnswer, youChoose) from BX_External_Functions import (autoTypeAnimation, StartupText, ShutdownText, UserInput, listen, speak, getRandomJoke, getFunFacts, setReminders, setTodo, terminateTimers, sendEmail, wishMe, setRenewal, ErrorMsg, offlineWarningMsg, checkForReminders) # Print a warning msg if there is no internet to prevent pywhatkit # from crashing the program due due no connection try: import pywhatkit except: offlineWarningMsg() #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- # Main #------------------------------------------------------------------------------------- def BAXTER(): command = UserInput() command=str(command).lower() #checkForReminders() #------------------------------------------------------------------------------------- # General Conversation (From Intents.py) #------------------------------------------------------------------------------------- #Greetings patterns, responses = greetings() if (command in patterns): results = (random.choice(responses)) autoTypeAnimation(results) speak(results) #Farewell patterns, responses = farewell() if (command in patterns): results = (random.choice(responses)) autoTypeAnimation(results) speak(results) #Thanks patterns, responses = thanks() if (command in patterns): results = (random.choice(responses)) autoTypeAnimation(results) speak(results) #No Response patterns, responses = noAnswer() if (command in patterns): results = (random.choice(responses)) autoTypeAnimation(results) speak(results) #------------------------- # Tell a Joke #------------------------- if ('joke' in command): try: joke = getRandomJoke() autoTypeAnimation(joke) speak(joke) except: ErrorMsg("get", "jokes") #------------------------- #------------------------- # Tell a Fun Fact #------------------------- if ('fact' in command): try: funFact = getFunFacts() autoTypeAnimation(funFact) speak(funFact) except: ErrorMsg("get", "fun facts") #------------------------- #------------------------------------------------------------------------------------- # Search Wikipedia (General Info) #------------------------------------------------------------------------------------- if ('weather' not in command): if ('who is' in command) or ('what is the' in command) or ('what is a' in command) or ("what is" in command): if ('time' not in command): if ('news' not in command): autoTypeAnimation('Searching Wikipedia...') speak('Searching...') command = command.replace("who is","") command = command.replace("what is the","") command = command.replace("what is a","") command = command.replace("what is","") try: results = wikipedia.summary(command, sentences = 2) autoTypeAnimation(results) speak(results) except: ErrorMsg("connect to", "Wikipedia") #------------------------------------------------------------------------------------- # Search Wolfram Alpha (Math/Conversions, Definitions) #------------------------------------------------------------------------------------- if ('news' not in command): if ('weather' in command) or ('calculate' in command) or ("what's" in command) or ('define' in command) or ("what" in command): autoTypeAnimation('Searching Wolfram Alpha...') speak('Searching...') command = command.replace("calculate","") command = command.replace("what's","") command = command.replace("define","") # Wolframalpha App Id appId = 'JH9XHR-W9J76L7H5A' try: # Wolfram Instance client = wolframalpha.Client(appId) res = client.query(''.join(command)) results = next(res.results).text autoTypeAnimation(results) speak(results) except: ErrorMsg("connect to", "Wolfram Alpha database") #------------------------------------------------------------------------------------- # Open Stuff on the Internet #------------------------------------------------------------------------------------- #Open Youtube Videos (Ex: 'Play __ on youtube') if ('youtube' in command): autoTypeAnimation("Launching Youtube...") speak('Launching Youtube') command = command.replace("youtube","") try: pywhatkit.playonyt(command) except: ErrorMsg("connect to", "Youtube") #Open Google Maps and Find The Location of A You Want if ('where is' in command): command = command.replace("where is","") autoTypeAnimation("Locating" + command + "...") speak('Locating' + command) webbrowser.open_new_tab("https://www.google.com/maps/place/" + command) #Search Stuff on Google if ('search' in command): command = command.replace("search", "") autoTypeAnimation("Searching" + command + " on Google") speak('Searching' + command) try: pywhatkit.search(command) except: ErrorMsg("connect to" , "Google") #Close Firefox if ('close firefox' in command): autoTypeAnimation("Terminating Firefox...") speak('Closing Firefox') command = command.replace("close firefox", "") browser = "firefox.exe" try: os.system("taskkill /f /im " + browser) except: ErrorMsg("close", "Firefox") #------------------------------------------------------------------------------------- # Open Stuff on the Computer #------------------------------------------------------------------------------------- #Open Windows Media Player and Auto Play the Playlist Called Music if ('play music' in command) or ('media player' in command) or ('drop the needle' in command): autoTypeAnimation("Launching music...") speak("Launching Music") command = command.replace("play music", "") command = command.replace("media player", "") command = command.replace("drop the needle", "") try: subprocess.Popen("C:\Program Files (x86)\Windows Media Player\wmplayer.exe /Playlist Music") except: ErrorMsg("open","Windows Media Player") #Close Windows Media Player if ('stop music' in command): autoTypeAnimation("Terminating music...") speak('Closing Music') command = command.replace("stop music", "") mediaPlayer = "wmplayer.exe" try: os.system("taskkill /f /im " + mediaPlayer) except: ErrorMsg("close", "Windows Media Player") #------------------------------------------------------------------------------------- # Set Reminders & Renewals #------------------------------------------------------------------------------------- if ('remind me' in command) or ('reminder' in command) or ('renew' in command): command = command.replace("remind me to", "") #If renew is mentioned in the command call the setRenewal Function if ('renew' in command): setRenewal() #Else, call the setReminders Function else: setReminders() #Call setReminders() from External Functions #------------------------------------------------------------------------------------- # Set ToDo #------------------------------------------------------------------------------------- if ('todo' in command): command = command.replace("add", "") command = command.replace("to the todo list", "") setTodo(command) #Call setTodo() from External Functions #------------------------------------------------------------------------------------- # Send E-Mails #------------------------------------------------------------------------------------- if ('email' in command): command = command.replace("email", "") sendEmail() #Call send E-Mail function fro External Functions #------------------------------------------------------------------------------------- # Stop Program/Script Command #------------------------------------------------------------------------------------- if ('stop' in command) or ('shutdown' in command) or ('quit' in command): speak("Shutting Down...") results = "Terminating program..." autoTypeAnimation(results) ShutdownText() terminateTimers() exit() #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------------ # Run The Program #------------------------------------------------------------------------------------------ def Main(): StartupText() wishMe() speak("How may I be of service?") while True: BAXTER() #------------------------------------------------------------------------------------------ RE: Help adding a loop inside a loop - deanhystad - Oct-09-2022 Take a look at the sched library unless you like reinventing the wheel. https://docs.python.org/3/library/sched.html If you like reinventing the wheel I would think about making an infinite iterator for "looping" through the reminder list. If your while True loop runs frequently, just check if the next(reminder) needs to sent. No need for an extra loop. RE: Help adding a loop inside a loop - Extra - Oct-09-2022 My while True loop runs very frequently (I hope to have it run 24/7), but how do I check if the next(reminder) needs to be sent, without adding another loop or crashing the current(while True) loop? And if I did Sched would that run at the same time as my while True loop, so they would both work "side by side" without issues? RE: Help adding a loop inside a loop - deanhystad - Oct-10-2022 Check the next event each time through your while True loop. If you run your outer loop frequently there is little difference between this: events = normal_iterator() # One time through while True: for next_event in events if time_to_execute_event(next_event): execute_event(next_event ) # Do other stuffAnd this events = make_a_forever_iterator() # Iterator that starts over when reaching end while True: next_event = next(events) if time_to_execute_event(next_event): execute_event(next_event ) # Do other stuffI think the sched library is a better choice. Schedule events when you start your program or when an event gets added, and then forget about it. The event scheduler will run the event when it is scheduled to run. RE: Help adding a loop inside a loop - Extra - Oct-10-2022 Ok, so I tried using sched by doing this: import sched import time from BX_External_Functions import checkForReminders # instance is created scheduler = sched.scheduler(time.time, time.sleep) print ('Checking for reminders...') event = scheduler.enter(1, 1, checkForReminders ) # executing the events scheduler.run()But if it doesn't find any reminders set for the current time it just exits, instead of returning and keep scanning until the current time matches the reminder time (ex: if the current time is 10:30 and the reminder is set for 10:32, the sched exits instead of staying open and running until the current time is 10:32, then once it's 10:32 it should still stay open/running in case there is another reminder set for a later time. It should only exit/stop once I quit the whole main program.) So how can I use the sched library to do that? RE: Help adding a loop inside a loop - deanhystad - Oct-10-2022 You don't schedule an event to check for the reminders, you schedule the reminders. RE: Help adding a loop inside a loop - Extra - Oct-10-2022 Sorry, I still don't understand. So I would have to set/add reminders using sched? Right now all my reminders are stored/set/added in an sqlite table with the columns (Reminder, Date, Time). I'm just looking for something to iterate through the table, comparing the current date & time with the Date & Time from the sqlite table and if it's a match it calls my popup function and if it's not a match it keeps iterating until it finds a match. Is there a way to iterate like that? RE: Help adding a loop inside a loop - deanhystad - Oct-10-2022 You create a schedule You read in reminders from the database. For each reminder you add an event to the schedule (enter or enterabs). If your program creates a new reminder it adds the reminder to the database and adds an event to the schedule. Inside your while True: loop you call schedule.run(blocking=False) When it is time to execute a reminder event, the schedule will do it automatically. RE: Help adding a loop inside a loop - Extra - Oct-10-2022 Thanks, I'm starting to understand it a bit more. The part I'm having trouble with is when I'm reading in the Reminders from my database do I read in all the reminders or just the ones where their dates/times match the current date/time? And if I read in all the reminders how would they (the Reminderpopup function) execute when their set date/time match the current date/time? This is what I have so far: import sched import time import sqlite3 from BX_External_Functions import checkForReminders from BX_Constants import MainDatabase, currentdate, currentTime #Create schedule scheduler = sched.scheduler(time.time, time.sleep) #Read in reminders from database # Connect to the database connection = sqlite3.connect(MainDatabase) cursor = connection.cursor() cursor.execute("SELECT Reminder,Date,Time FROM Reminders") Results = cursor.fetchall() connection.commit() connection.close() #For each reminder, add an event to the schedule (enter) for row in Results: print(row) #If a new reminder is created, add it to the database & add an event to the schedule #Inside Baxter's while True loop, call schedule.run(blocking=False)-------- This would be my SQlite statement for reading in only the reminders where their date/time match the current date/time: import sqlite3 from BX_Constants import MainDatabase, currentdate, currentTime #Read in reminders from database # Connect to the database connection = sqlite3.connect(MainDatabase) cursor = connection.cursor() # Get Reminders where their dates & times match today's date & time cursor.execute("SELECT Reminder FROM Reminders WHERE Date = ? AND Time = ?",(currentdate, currentTime)) Results = cursor.fetchall() connection.commit() connection.close() RE: Help adding a loop inside a loop - deanhystad - Oct-10-2022 Schedule all the reminders when you start the program. I don't know if you want to delete reminders that happened in the past or have them all sent when the program starts. Here's a small example that schedules a reminder to print the scheduled time of the reminder. The example jumps through a few hoops to look like I am using an absolute time without forcing you to wait to see the reminder. from datetime import datetime, timedelta from sched import scheduler import time schedule = scheduler(time.time, time.sleep) # Make a reminder that happens five seconds from now now = datetime.now() scheduled_time = now + timedelta(seconds=5) action = lambda: print(f"The scheduled time is", scheduled_time) # Create an event to execute the reminder schedule.enterabs(scheduled_time.timestamp(), 1, action) print("The start time is", now) schedule.run(True) print("The current time is", datetime.now())You will not set blocking=True when you schedule.run() because you don't want it blocking your while True: loop. |