import time
import os
T = int(input("Enter desired time for the timer - "))
t = time.localtime(time.time())
def Timer():
while ((t.tm_sec) != T+(t.tm_sec)):
return t
else:
os.system("start C:/Users/Public/Music/Sample Music")
Timer()
I have been working on this timer and can't get it to work. Basically, I want it to play the song I have in my system when the time is up. I have been trying to write this program and I can't understand why my code doesn't run the way I want it to. Could someone please point out if there's a mistake in it?
What's wrong with your code specifically is this condition
(t.tm_sec) != T+(t.tm_sec)
The problem is that t's value was set when you did (t.tm_sec) != T+(t.tm_sec). Once that is set, the same value of t will be used. I think you assumed that t will be recomputed every time in the while statement. To recompute t every time you can do:
import time
import os
T = int(input("Enter desired time for the timer - "))
snap_time = time.localtime(time.time())
def Timer():
t = time.localtime(time.time())
while t.tm_sec < (T + snap_time.tm_sec):
t = time.localtime(time.time())
os.system("start C:/Users/Public/Music/Sample Music")
Timer()
t.tm_sec is fixed, so unless T is 0 the condition will never be False, so the else block will never be executed. On top of that there is return in the loop, which mean it will run only one iteration and exit the function. Try
T = int(input("Enter desired time for the timer - ")) + time.time()
def Timer():
while time.time() < T:
pass
else:
os.system("start C:/Users/Public/Music/Sample Music")
You can also remove the else
def Timer():
while time.time() < T:
pass
os.system("start C:/Users/Public/Music/Sample Music")
I don't think your example makes proper use of while (and return). How about a much simpler version:
import time
import os
T = int(input("Enter desired time for the timer - "))
def Timer():
time.sleep(T)
os.system("start C:/Users/Public/Music/Sample Music")
Timer()
Related
I have this code to stop a function at a specific time. I would loop through the function and then break the function, if it takes too long, is there a better way to do it?
import time
def function_one()
rec = (time.time())
print("im starting")
ans = str(time.time() - rec)
ans = (round(float(ans), 15))
print("this is where im doing something code")
while ans < 10:
return function_one()
break
You can make it simpler like this:
import time
def function_one():
start_time = time.time()
while True:
print('Function doing something ...')
if time.time() - start_time > 10:
break
function_one()
Here, I'm using a while loop just to keep the function running, but that depends on the details of your function.
In general, what you need is:
set the start time
do whatever the function is supposed to be doing;
check if it's been running for too long and, in case it has, you can simply return.
So, something like:
import time
def function_one():
start_time = time.time()
# do your job
if time.time() - start_time > 10:
return something
function_one()
If you want to stop a function after a set amount of time has passed I would use a while loop and do something like this.
import time
def function_one():
start = (time.time()) #start time
limit = 1 #time limit
print("im starting")
while (time.time() - start) < limit:
#input code to do here
pass
print(f"finished after {time.time() - start} seconds")
function_one()
Background: I'm using as Raspberry Pi rev 2 B to run a nature sound white noise generator of sorts that will randomly play audio tracks of varying length based on the time of night/morning. Some tracks are only a minute, some are several hours long. I'm looking for a way to check the time and change which type of sounds play based on time.
Current issue: I can start the appropriate audio for the time when the program first executes, but the timeloop execution stops polling once omxplayer starts up.
I have tried to call OMXPlayer without interrupting the time checker that determines what kind of audio to play, but once the audio playback starts I have been unable to continue checking time. Even if the play_audio() function wasn't recursive I would still like a way for the time checker to continue executing while the audio plays
#!/usr/bin/env python
import datetime, time, os, subprocess, random
from timeloop import Timeloop
from datetime import timedelta
from time import sleep
from omxplayer.player import OMXPlayer
from pathlib import Path
tl = Timeloop()
running_cycle = "off" # default value for the time cycle currently running
#function to check current time cycle
def check_time () :
dt_now = datetime.datetime.now()
t_now = dt_now.time()
t_night = datetime.time(hour=2,minute=0)
t_twilight = datetime.time(hour=4,minute=45)
t_morning = datetime.time(hour=7,minute=0)
t_end = datetime.time(hour=10,minute=0)
if t_night <= t_now < t_twilight:
return "night"
elif t_twilight <= t_now < t_morning:
return "twilight"
elif t_morning <= t_now < t_end:
return "morning"
else:
return "off"
# function that plays the audio
def play_audio (time_cycle):
subprocess.call ("killall omxplayer", shell=True)
randomfile = random.choice(os.listdir("/home/pi/music/nature-sounds/" + time_cycle))
file = '/home/pi/music/nature-sounds/' + time_cycle + '/' + randomfile
path = Path(file)
player = OMXPlayer(path)
play_audio (time_cycle)
# function that determines whether to maintain current audio cycle or play another
def stay_or_change():
global running_cycle
current_cycle = check_time()
if running_cycle != current_cycle:
if current_cycle == "off" :
player.quit()
else:
running_cycle = current_cycle
print "Now playing: " + running_cycle + " #{}".format(time.ctime())
play_audio(running_cycle)
#starts timeloop checker to play audio - works until stay_or_change() calls play_audio
#tl.job(interval=timedelta(seconds=10))
def job_10s():
print "10s job - running cycle: " + running_cycle + " - current time: {}".format(time.ctime())
stay_or_change()
# starts the timeloop
if __name__ == "__main__":
tl.start(block=True)
I have also tried running OMXPlayer with subprocess.run() but it still seems to hang up after the player starts. I'm completely open to any recommendations for background threading media players, process daemons, or time based execution methods.
I'm new to Python.
I had the recursion all wrong so it got caught in an infinite loop and the timeloop function wasn't really viable for this solution. Instead I had a function that played the sound, and then called the function that checked the time and plays from the appropriate sub-directory (or play nothing and wait).
Here's what I managed to come up with:
#!/usr/bin/env python
import datetime, time, os, subprocess, random
from datetime import timedelta
from time import sleep
from omxplayer.player import OMXPlayer
def check_time () :
dt_now = datetime.datetime.now()
t_now = dt_now.time()
t_night = datetime.time(hour=0,minute=0)
t_twilight = datetime.time(hour=5,minute=45)
t_morning = datetime.time(hour=7,minute=45)
t_end = datetime.time(hour=10,minute=0)
if t_night <= t_now < t_twilight:
return "night"
elif t_twilight <= t_now < t_morning:
return "twilight"
elif t_morning <= t_now < t_end:
return "morning"
else:
return "off"
def play_audio (time_cycle):
randomfile = random.choice(os.listdir("/home/pi/music/nature-sounds/" + time_cycle))
file = '/home/pi/music/nature-sounds/' + time_cycle + '/' + randomfile
print "playing track: " + randomfile
cmd = 'omxplayer --vol -200 ' + file
subprocess.call (cmd, shell=True)
what_to_play()
def what_to_play():
current_cycle = check_time()
if current_cycle == "off" :
print "sounds currently off - #{}".format(time.ctime())
time.sleep(30)
what_to_play()
else:
print "Now playing from " + current_cycle + " #{}".format(time.ctime())
play_audio(current_cycle)
what_to_play()
I've been trying to break a loop which is meant to look for a file in a certain location. My intention is to make my script look for that file for a certain time and then break whether the file is found or not but I can't get any idea.
How can I make the script wait for a certain time and then break when the time is up?
This is my script at this moment:
import os
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
time_limit = 5
while not os.path.exists(file_path):
time.sleep(1)
#is there any logic I can apply here to make the following line valid
# if waiting_time>=time_limit:break
print("Time's up")
Calculate the elapsed time by doing actual time minus start time by using time.time() function and assign a variable (file_exists in this code) which will be modified and check whether the file exist or not and use it for the loop.
As below:
import os
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
time_limit = 5
start = time.time()
file_exists = os.path.exists(file_path)
while not file_exists:
time.sleep(1)
file_exists = os.path.exists(file_path)
elapsed = time.time() - start
if elapsed >= time_limit:
break
else:
print("File exist.")
print(elapsed)
print("Time's up")
def exists_timeout(path, timeout):
"""Return once <path> exists, or after <timeout> seconds,
whichever is sooner
"""
timer = timeout
while (not os.path.exists(path)) and timer > 0:
time.sleep(1)
timer -= 1
import os
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
cTime=0
time_limit = 5
while cTime<time_limit:
if os.path.exists(file_path)==False:
cTime=cTime+1
time.sleep(1)
else:
pass
if cTime==5:
responce="Time's Up"
else:
responce='Found'
print(responce)
As roganjosh commented, it would be simpler if you used time stamps. I have added relevant code below:
import os
import time
from datetime import datetime, timedelta
file_path = r"C:\Users\WCS\Desktop\item.txt"
time_limit = datetime.now() + timedelta(seconds=5)
present = datetime.now()
while (not os.path.exists(path)) and present < time_limit:
present = datetime.now()
if present >= time_limit:
print("Time's up")
break
time.sleep(1)
Here's how to do it with the threading.Timer() class. These can be configured to delay a specified amount of time and the call as function of your choosing.
import os
from threading import Timer
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
# Timer callback function.
def timeout():
global time_ran_out
time_ran_out = True
time_limit = 5
time_ran_out = False # Define variable the callback function modifies.
timer = Timer(time_limit, timeout) # Create a timer thread object.
timer.start() # Start the background timer.
while not os.path.exists(file_path):
time.sleep(1)
if time_ran_out:
print('Times up!')
break
print("Done")
To check for the availability of a file in a certain location you can try the following. The script will break as soon as the file is found otherwise it will wait upto 5 seconds for the file to be available before breaking.
import os
import time
file_path = r"C:\Users\WCS\Desktop\item.txt"
time_to_wait = 5
time_counter = 0
while not os.path.exists(file_path):
time.sleep(1)
time_counter += 1
if time_counter > time_to_wait:break
print("done")
I have the following code and I want to stop the program if the condition is not true for a certain period of time. Suppose the condition (sum>99999) is false for a period of 10 seconds, then this program stops and gives present sum values. I am on Windows. Any idea how to do it in Windows.
for j in i:
sum=sum+A[j]
if(sum>99999):
print("Current sum is",sum)
This should accomplish what you're describing.
import time
import sys
start_time = time.time()
for j in i:
sum = sum + A[j]
if sum > 99999:
print("Current sum is ", sum)
start_time = time.time() # reset timer if the condition becomes true
elif time.time() - start_time >= 10:
print("Current sum is ", sum)
sys.exit()
Try this:
import time
import sys
start = time.time()
for j in i:
sum += A[j]
if sum > 99999:
print(sum)
elif time.time() - start > 10:
print(sum)
break # if you just want to exit the loop or sys.exit() if you want to exit the program
Sometimes an iteration is heavy enough to render technique proposed by other answers pretty useless. If you don't have access to break execution upon condition, this or that recipes would be helpful.
I will copy the simpler one (and the one I prefer in my code):
import threading
def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
class InterruptableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = None
def run(self):
try:
self.result = func(*args, **kwargs)
except:
self.result = default
it = InterruptableThread()
it.start()
it.join(timeout_duration)
if it.isAlive():
return default
else:
return it.result
import sys
import time
start_time = time.time()
time_limit = 2
if (comdition):
if((time.time() - start_time) > time_limit):
sys.exit()
else:
#more stuff here
I am trying to create a stopwatch that starts and stops through the user pressing the enter. Once to start and again to stop. The start works perfectly but the stopping section is not working. I've tried creating a variable called stop that is like so:
stop = input("stop?")
But it's still not working.
import time
def Watch():
a = 0
hours = 0
while a < 1:
for minutes in range(0, 60):
for seconds in range(0, 60):
time.sleep(1)
print(hours,":", minutes,":", seconds)
hours = hours + 1
def whiles():
if start == "":
Watch()
if start == "":
return Watch()
def whiltr():
while Watch == True:
stop = input("Stop?")
#Ask the user to start/stop stopwatch
print ("To calculate your speed, we must first find out the time that you have taken to drive from sensor a to sensor b, consequetively for six drivers.")
start = input("Start?")
start = input("Stop")
whiles()
Perhaps all you need is something simple like:
import time
input('Start')
start = time.time()
input('Stop')
end = time.time()
print('{} seconds elapsed'.format(end-start))
Should probably use the time function instead of
def Watch():