Run script at specific time with Python - python

I want to run the following at 22:00 PM everyday using import datetime.
I'm trying to use a codeRan boolean to trigger it, but I can't get it to work. It's always False:
import datetime
timeNow = datetime.datetime.now() # 2022-10-31 10:23:10.461374
timeHour = timeNow.strftime("%H") # 22
timeFull = timeNow.strftime("%X") # 10:21:59
timeAMPM = timeNow.strftime("%p") # AM or PM
codeRan = False
if timeHour == "22" and codeRan == False:
print(timeHour + " That is correct!")
codeRan = True
elif timeHour == "22":
print("Script already ran. Wait 24 hours")
else:
print("Not time yet, it's only " + timeFull + ". The script will run at 22:00" + timeAMPM)

The code as you wrote it will run the code print(timeHour + " That is correct!") and print 22 That is correct! if your script is run between 10pm-11pm. However, you have not included a loop in your code, so you would need to use some external method to call the script frequently to check whether it is time to run your other script. In linux, you could use crontab to schedule this to run every five minutes, but then if you were planning to do that you could just use crontab to schedule it to run at 10 pm. In windows, TaskScheduler can also be used.
If you want to use python, you really have three options which I can think of (realistically probably way more).
use a while loop (probably the easiest yet least elegant solution because the code would run 24/7
while True:
{your example code here}
Use cron or TaskScheduler
Use subprocess.call to do #2 with Python. Could even check sys.platform to determine whether you are on Linux or Windows.
Check the time, then sleep until it is time to run the code. Again, not great because it means the process must stay alive this entire time.
Additionally, while your method or comparing timeNow.strftime("%H") == '22' does work you also could use time.hour == 22.

I don't know the requirements of your script, but if you simply want to solve the proposed problem, a simple while is missing:
while not codeRan:
if timeHour == "22" and codeRan == False:
print(timeHour + " That is correct!")
codeRan = True
elif timeHour == "22":
print("Script already ran. Wait 24 hours")
else:
print("Not time yet, it's only " + timeFull + ". The script will run at 22:00" + timeAMPM)
To prevent checking without a minimum wait, you can insert a sleep at the end of each iteration:
while not codeRan:
if timeHour == "25" and codeRan == False:
print(timeHour + " That is correct!")
codeRan = True
elif timeHour == "22":
print("Script already ran. Wait 24 hours")
else:
print("Not time yet, it's only " + timeFull + ". The script will run at 22:00" + timeAMPM)
time.sleep(num_of_seconds)

Related

Getting skipped out of the loop without letting me type

So I made a very simple Auto-typer and want to be able to run it again or quit it.
All works perfectly fine but at the end the "ending = input()" doesnt let me type it just exits out of the programm. Any reason why?
import pyautogui
import time
import os
def clearConsole():
command = 'clear'
if os.name in ('nt', 'dos'): # If Machine is running on Windows, use cls
command = 'cls'
os.system(command)
break_loop = 1
while break_loop <= 1:
secs_inbetween_actions = float(input("""
Seconds between actions(should be float but int is also ok): """))
no_of_lines = int(input("""
How many Lines do you want to write?(Only int): """))
time_between_action = int(input("""
How long should the time between enter and writing be?: """))
lines = ""
print("""
Write your Text under this message (You have """ + str(no_of_lines) + """ line(s) to wite)
""")
for i in range(no_of_lines):
lines += input() + "\n"
print("-------------------------------------")
while time_between_action > 0:
time_between_action = time_between_action - 1
print('Time Left until writing -+==> ' + str(time_between_action))
time.sleep(1)
print("-------------------------------------")
pyautogui.typewrite(lines, interval=secs_inbetween_actions)
ending = input("If you want to use this aplication once again type 'y' + 'enter key' ,if not press the 'enter key': ")
if ending == "y":
break_loop = 1
clearConsole()
else:
break_loop += 1
This is a rather fun little problem. It occurs, as #Barmar notes, because pyautogui.typewrite() is writing to the console for you. I incorrectly thought that it was not happening when there was no delay between actions, which was a far more puzzling little problem.
In this case the solution is easy: add after your typewrite():
if lines:
input()
To absorb what has just been typed for you.

Using variables from another Python file & function in module not running?

This is a continuation of my previous question, with more details. (Formatting should be better, as I am on a computer now!)
So I am trying to create a game in Python, where if a number reaches a certain amount you lose. You try to keep the number under control to keep it from reaching the number it shouldn't. Now, I had an error in my previous question that said:
AttributeError: module 'core temp' has no attribute 'ct'
However, I've modified my code a bit and no longer get any errors. However, when I run the code, a function in a module I made won't run.
To make sure that anyone trying to figure out the solution has all the resources they need, I'll provide all my code.
This is the code in the file main.py:
from termcolor import colored
from time import sleep as wait
import clear
from coretemp import ct, corestart
print(colored("Begin program", "blue"))
wait(1)
clear.clear()
def start():
while True:
while True:
cmd = str(input("Core> "))
if cmd == "help":
print(
"List of commands:\nhelp - Show a list of commands\ntemp - Show the current temperature of the core in °C\ninfo - Show core info\ncool - Show coolant control"
)
break
elif cmd == "temp":
if ct < 2000:
print(
colored("Core temperature: " + str(ct) + "°C",
"green"))
elif ct < 4000:
print(
colored("Core temperature: " + str(ct) + "°C",
"yellow"))
elif ct >= 3000:
print(
colored("Core temperature: " + str(ct) + "°C", "red"))
print("Welcome to SprinkleLaboratories Main Core System")
wait(1)
print(
"\nYou have been hired as the new core operator.\nYour job is to maintain the core, and to keep the temperature at a stable number. Or... you could see what happens if you don't..."
)
wait(3)
print("\nTo view available commands, use the \"help\" command!")
cont = input("Press enter to continue> ")
clear.clear()
start()
corestart(10)
This is the code in the file clear.py:
print("clear.py working")
def clear():
print("\n"*100)
This is the code in the file coolant.py:
from time import sleep as wait
print("coolant.py working")
coolam = 100
coolactive = False
def coolact():
print("Activating coolant...")
wait(2)
coolactive = True
print("Coolant activated. "+coolam+" coolant remaining.")
This is the code in the file coretemp.py:
from coolant import coolactive
from time import sleep as wait
print("coretemp.py working")
ct = 0
def corestart(st):
global ct
ct = st
while True:
if coolactive == False:
ct = ct + 1
print(ct)
wait(.3)
else:
ct = ct - 1
print(ct)
wait(1)
Note:
Some of the code in the files are incomplete, so some things may seem like they do nothing at the moment
If you want to see the code itself, here is a link to a repl.it:
Core
Note #2:
Sorry if things aren't formatted correctly, if I did something wrong in the question, etc. I'm fairly new to asking questions on Stackoverflow!
You can't normally have two things running at once, so when you are in the while True of start() you never ever get to the next bit of your code because while True is true forver.
So, threading to the rescue! Threads allow you to have one thing going on in one place and another thing going on in another. If we put the code to update and print the temperature in its own thread, we can set that running and then go ahead and start doing the infinite loop in start() while our thread keeps running in the background.
One other note, you should be importing coretemp itself, rather than importing variables from coretemp, otherwise you will be using a copy of the variable ct in main.py when you actually want to be using the real value of ct from coretemp.
Anyhow, here's a minimal update to your code that shows the use of threads.
main.py:
from termcolor import colored
from time import sleep as wait
import clear
import coretemp
import threading
print(colored("Begin program", "blue"))
wait(1)
clear.clear()
def start():
while True:
while True:
cmd = str(input("Core> "))
if cmd == "help":
print(
"List of commands:\nhelp - Show a list of commands\ntemp - Show the current temperature of the core in °C\ninfo - Show core info\ncool - Show coolant control"
)
break
elif cmd == "temp":
if coretemp.ct < 2000:
print(
colored("Core temperature: " + str(coretemp.ct) + "°C",
"green"))
elif coretemp.ct < 4000:
print(
colored("Core temperature: " + str(coretemp.ct) + "°C",
"yellow"))
elif coretemp.ct >= 3000:
print(
colored("Core temperature: " + str(coretemp.ct) + "°C", "red"))
print("Welcome to SprinkleLaboratories Main Core System")
wait(1)
print(
"\nYou have been hired as the new core operator.\nYour job is to maintain the core, and to keep the temperature at a stable number. Or... you could see what happens if you don't..."
)
wait(3)
print("\nTo view available commands, use the \"help\" command!")
cont = input("Press enter to continue> ")
clear.clear()
coretemp.corestart(10)
t1 = threading.Thread(target=coretemp.coreactive)
t1.start()
start()
coretemp.py:
from coolant import coolactive
from time import sleep as wait
print("coretemp.py working")
ct = 0
def corestart(st):
global ct
ct = st
def coreactive():
global ct
while True:
if coolactive == False:
ct = ct + 1
print(ct)
wait(.3)
else:
ct = ct - 1
print(ct)
wait(1)
You can see we still have some work to do to make the output look nice and so on, but hopefully you get the general idea.

jupyter notebook not executing codes

I starting learning python recently and so far no problem. Yesterday, the jupyter notebook stopped executing code. I have searched online,restarted the kernel, restarted my windows machine and tried to find a way to understand what it is doing so that I can continue, but I have not found a the solution or the reason that my code is not being executed anymore. I am running my code on a windows machine,chrome on windows. I did not intall the jupyter on my machine. I running it off the azure network.
Please help.
Thanks,
David
The program was an is still in 'code' mode. To execute, we are told to execute via "ctrl + enter". I had done that for the last 3 weeks without problem till now.
import os
string_container = ""
add_container = 0
def adding_report(integerToAdd):
Total = 0
Total = Total + integerToadd
# add_container = 0
while True:
a = input("Input a number: ")
if a.digit():
string_container += a + "\n"
add_container += int(a)
else:
if a == 'A':
print(Add_container)
else:
if a == 'T':
print(string_container)
else:
if a=="q":
os._exit(0)
else:
print("invalid input")
I think i got it. If you write like this, then you can run it for the first time. But from the second time it will not be executed. Because jupyter only clear that code block output, but do not release the while loop.
while True:
a = input("Input a number: ")
if a.isdigit():
string_container += a + "\n"
add_container += int(a)
else:
if a == 'A':
print(Add_container)
else:
if a == 'T':
print(string_container)
else:
if a=="q":
os._exit(0)
else:
print("invalid input")
You should put your code in a try-catch block, like this.
try:
while True:
a = input("Input a number: ")
if a.isdigit():
string_container += a + "\n"
add_container += int(a)
else:
if a == 'A':
print(Add_container)
else:
if a == 'T':
print(string_container)
else:
if a=="q":
os._exit(0)
else:
print("invalid input")
except KeyboardInterrupt:
pass
So you have to
1. Select restart the kernel and clear output
2. Add try-catch so you can use "kernel interrupt" to kill the while loop
3. Whenever you finish using this while loop, select "kernel" -> "interrupt" to kill it completely
Hope that help

Performing tasks after a certain amount of time in python

I am currently writing an audio playout system using python3 and afplay. I have run into a problem where I cannot get it to automatically go to the next song in the playlist, whilst still allowing for user control.
for i in range(metadata["length"] - start):
i += start
curr = songs[i]
play(directory + curr)
paused_bool = False
while True:
clear()
print("Currently playing track #" + str(i+1) + ", called '" + curr + "', from playlist '" + metadata["name"] + "'.")
command = input("What would you like to do? 'play', 'stop/exit', 'pause', or 'skip/next': ")
if command == "play" or command == "pl":
if not paused_bool:
print("It is already playing.")
else:
play(directory + curr)
elif command == "stop" or command == "st" or command == "quit" or command == "q" or command == "exit":
stop()
return
elif command == "pause" or command == "p" or command == "pa":
if paused_bool:
print("The audio shall remain paused.")
paused_bool = True
stop()
elif command == "move the hell on" or command == "skip" or command == "next" or command == "n" or command == "s" or command == "":
stop()
break
clear()
Above is the code that plays each song inside a folder. I want to be able to manually go to the next song using the "next" command, but also have it automatically go to the next after some time has passed, specifically the length of the song.
I have tried using the threading package, but I then run into a problem when I can't break the while loop from a function:
for i in range(metadata["length"] - start):
i += start
curr = songs[i]
play(directory + curr)
paused_bool = False
while True:
clear()
def auto():
time.sleep( length( curr_song ) )
stop() # stop() & break goes to the next song
break
thread = Thread(target = auto, args = [])
thread.start()
print("Currently playing track #" + str(i+1) + ", called '" + curr + "', from playlist '" + metadata["name"] + "'.")
command = input("What would you like to do? 'play', 'stop/exit', 'pause', or 'skip/next': ")
if command == "play" or command == "pl":
if not paused_bool:
print("It is already playing.")
else:
play(directory + curr)
elif command == "stop" or command == "st" or command == "quit" or command == "q" or command == "exit":
stop()
return
elif command == "pause" or command == "p" or command == "pa":
if paused_bool:
print("The audio shall remain paused.")
paused_bool = True
stop()
elif command == "move the hell on" or command == "skip" or command == "next" or command == "n" or command == "s" or command == "":
stop()
break
clear()
I apologise that the question is incredibly convuluted, but any help would be greatly appreciated.
You may want to use scheduler.
It would change somewhat the logic of your code, but it would likely be more functional.
You would, by default, schedule an event for playing the next song (use enter or enterabs). You could get the running time of the current song so you know when to schedule the next one.
If "next" is selected, you would cancel the previous event and schedule two others: 1) a new one for immediate execution, play the next song, 2) play the following song.

Parallel While loops

I am writing a Python program, and I want to run two while loops at the same time. I am pretty new to Python, so this could be a elementary mistake/misconception. The project is having a Raspberry Pi monitor a sump pump to make sure that it is working, and if not, send an email to the specified recipients. One loop is going to interact with the user, and respond to commands send to it in real time through SSH.
while running is True:
user_input = raw_input("What would you like to do? \n").lower()
if user_input == "tell me a story":
story()
elif user_input == "what is your name":
print "Lancelot"
elif user_input == "what is your quest":
print "To seek the Holy Grail"
elif user_input == "what is your favorite color":
print "Blue"
elif user_input == "status":
if floatSwitch == True:
print "The switch is up"
else:
print "The switch is down"
elif user_input == "history":
print log.readline(-2)
print log.readline(-1) + "\n"
elif user_input == "exit" or "stop":
break
else:
print "I do not recognize that command. Please try agian."
print "Have a nice day!"
The other loop will be monitoring all of the hardware and to send the email if something goes wrong.
if floatSwitch is True:
#Write the time and what happened to the file
log.write(str(now) + "Float switch turned on")
timeLastOn = now
#Wait until switch is turned off
while floatSwitch:
startTime = time.time()
if floatSwitch is False:
log.write(str(now) + "Float switch turned off")
timeLastOff = now
break
#if elapsedTime > 3 min (in the form of 180 seconds)
elif elapsedTime() > 180:
log.write(str(now) + " Sump Pump has been deemed broaken")
sendEmail("The sump pump is now broken.")
break
Both of these functions are critical, and I want them to run in parallel, so how do I get them to run like that? Thanks for everyone's help!
Stuff running in parallel? Try using threading - see for example this module in the standard library, or the multiprocessing module.
You will need to create a thread for each of the while loops.
This post has some good examples of how to use threads.
On some other notes, I can't help noticing you use if variable is True: instead of if variable: and if variable is False: instead of if not variable:, the alternatives given being more normal and Pythonic.
When you do elif user_input == "exit" or "stop": this will always be true because it is actually testing if (use_input == "exit") or ("stop"). "stop" is a non-empty string, so it will always evaluate to True in this context. What you actually want is elif user_input == "exit" or user_input == "stop": or even elif user_input in ("exit", "stop"):.
Finally when you do log.write(str(now) + "Float switch turned off") it would probably better to do string formatting. You could do log.write("{}Float switch turned off".format(now)), or use % (I don't know how to do that since I only used Python 2.x for a few weeks before moving to 3.x, where % has been deprecated).

Categories

Resources