I'm trying to create an alarm clock with multiple alarms, which are set from a text file with a specific time each line, but at the moment it's only working if I set only one time. What am I doing wrong? Here is the code I have right now:
import time
from playsound import playsound
Time = time.strftime('%H:%M')
with open('alarms.txt') as f:
alarms = f.readlines()
for alarm in alarms:
while Time != alarm:
print('The time is: ' + Time)
Time = time.strftime('%H:%M')
time.sleep(1)
continue
if Time == alarm:
playsound('alarm.mp3')
And my alarms.txt is setup like HH:MM:
18:45
18:55
From the information given so far, my thought is this:
Remember that readlines() reads in lines and returns strings with the newline character still trailing.
You need to compare the Time to the lines with the newline character removed.
import time
from playsound import playsound
Time = time.strftime('%H:%M')
with open('alarms.txt') as f:
alarms = f.readlines()
for alarm in alarms:
alarm = alarm.rstrip('\n')
while Time != alarm:
print('The time is: ' + Time + '\n')
Time = time.strftime('%H:%M')
time.sleep(1)
continue
if Time == alarm:
playsound('alarm.mp3')
This also assumes, of course, that the times in the text file are in the desired chronological order.
Related
i Try to set up my Raspberry pi with a fan. It should log the Temperature every 5 minutes and write it to a .csv-file with a Python Script. If the Temperature is hotter than 52 Degrees Celsius, it shoud turn on a USB-Hub, and turn it of if it is below that value. For now, i created a little website, to see my logged data. And here is my question: as you can see in the screenshot, it tells me sometimes [HOT] and sometimes [OK] for the same Values? Also it is not sepperating the Data like a want it to seperate (over/under 52 Degrees Celsius).
Screenshot from my little website (This only displays my .csv-File)
My .py-code:
from gpiozero import CPUTemperature
from time import sleep, strftime, time
from datetime import datetime, timedelta
from threading import Timer
import matplotlib.pyplot as plt
v=datetime.today()
w = v.replace(day=v.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)
delta_t=w-v
secs=delta_t.total_seconds()
cpu = CPUTemperature()
plt.ion()
x = []
y = []
def write_tempHot(temp):
with open("/var/www/html/cpuTemp.csv", "a") as log:
log.write("{0}{1}\n".format(strftime("%Y-%m-%d %H:%M:%S = [HOT] "),str(temp)))
def write_tempLow(temp):
with open("/var/www/html/cpuTemp.csv", "a") as log:
log.write("{0}{1}\n".format(strftime("%Y-%m-%d %H:%M:%S = [OK] "),str(temp)))
def clearTemp():
filename = "/var/www/html/cpuTemp.csv"
# opening the file with w+ mode truncates the file
f = open(filename, "w+")
f.close()
while True:
temp = cpu.temperature
if temp > 52:
temp = cpu.temperature
write_tempHot(temp)
plt.pause(300)
t = Timer(secs, clearTemp)
t.start()
else:
temp = cpu.temperature
write_tempLow(temp)
plt.pause(300)
t = Timer(secs, clearTemp)
t.start()
(Also dont mind for the clearTemp()-function, i want to clear the .csv-file once a day)
Does anybody have n idea, why the results are that kind of strange?
Greetings & Thanks a lot!
Your comparison is
if temp > 52
when it should be
if temp >= 52.0
because otherwise your temperature Hi will only match if it is 53C or above.
I'd also use time.sleep() instead of plt.pause().
For your logfile, you've got two functions to write to your logfile, I'd use one instead:
def write_log(temp):
fmt = """{when} = [{option}] {temp}"""
datefmt = """%Y-%m-%d %H:%M:%S"""
option = "OK"
with open("/var/www/html/cpuTemp.csv", "a") as log:
when = datetime.now().strftime(datefmt)
if temp >= 52.0:
option = "HOT"
log.write(fmt.format(when=when, option=option, temp=temp))
Finally, I do not understand why you want to truncate your logfile every 5 minutes.
Here's what I'm trying to do: I'd like to run the following function every hour for 24 hours. This function collects data from an api, appends values to a dictionary and saves it as a json file for later use. The code I'm running works ok but it is not elegant as I have to KeyboardInterrupt to stop it. I'd like for the script to stop running after 24hrs and to print at each hour: print('data successfully collected at ' + time.ctime()
def weather_collect():
url = 'http://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&appid={}&units=metric'
response = requests.get(url.format(lat,lon, api_key))
r = response.json()
data['temperature'].append(r['main']['temp'])
data['humidity'].append(r['main']['humidity'])
data['pressure'].append(r['main']['pressure'])
data['visibility'].append(r['visibility'])
data['wind_speed'].append(r['wind']['speed'])
data['time'].append(time.ctime())
with open('data.json', 'w') as f:
f.write(json.dumps(data))
return data
schedule.every(1).hour.do(weather_collect)
while 1:
schedule.run_pending()
time.sleep(1)
Instead of:
schedule.every(1).hour.do(weather_collect)
while 1:
schedule.run_pending()
time.sleep(1)
Put this one:
for i in range(25):
weather_collect()
print('data successfully collected at ' + time.ctime())
sleep(3600) # sleep one hour
exit()
One solution might be to add a counter you increment by 1 every time the loop executes.
And break the "while 1" loop on the 24th iteration.
apologies if this question has been asked somewhere before, but I couldn't find a solution / info i was looking for.
So: I am running a raspberry pi 0W with a python script reading 4 temperature sensors monitoring some stuff at home. I am reading these sensors every 2 minutes and write the output into a CSV (for the time being sufficient for me). When I ssh my PI and run my script in TMUX, I realised that when calling my "Sensordata.csv" it only updates, once I close the script in my TMUX session. Ideally I want my "Sensordata.CSV" file update after each polling cycle.
I believe its not the code, as my code opens, writes and closes the file while running in the shell normally. Hope someone can help me out =)
import time
import csv
from datetime import datetime
def get_temp(dev_file):
f = open(dev_file,"r")
contents = f.readlines()
f.close()
index = contents[-1].find("t=")
if index != -1 :
temperature = contents[-1][index+2:]
cels =float(temperature)/1000
return cels
time_for_csv=time.asctime( time.localtime(time.time()))
f=open("Sensordata.csv", "a")
c=csv.writer(f)
if __name__ =="__main__":
while True:
dateTimeObj = datetime.now()
timestampStr = dateTimeObj.strftime("%d-%b-%Y (%H:%M:%S.%f)")
temp = get_temp("//sys/bus/w1/devices/28-0301a2799ec4/w1_slave")
temp2 = get_temp("//sys/bus/w1/devices/28-0301a2790081/w1_slave")
temp3 = get_temp("//sys/bus/w1/devices/28-012020be268d/w1_slave")
tempout = get_temp("//sys/bus/w1/devices/28-00000b0f6540/w1_slave")
print('Current Timestamp : ', timestampStr, "28-00000b0f6540 - Outside Sensor", tempout)
print('Current Timestamp : ', timestampStr, "28-0301a2799ec4 - Floorheating out", temp)
print('Current Timestamp : ', timestampStr, "28-0301a2790081 - Floorheating in", temp2)
print('Current Timestamp : ', timestampStr, "28-012020be268d - Room Sensor", temp3)
f = open("Sensordata.csv", "a")
c = csv.writer(f)
c.writerow([timestampStr, temp, temp2, temp3, tempout])
f.close()
time.sleep(120)
I don't think that Tmux is part of the issue.
Try removing these 3 lines of code in your script:
time_for_csv=time.asctime( time.localtime(time.time()))
f=open("Sensordata.csv", "a")
c=csv.writer(f)
time_for_csv is unused.
When opening a file for writing or appending, a safer way is to use the following:
with open("Sensordata.csv", "a") as f:
c=csv.writer(f)
c.writerow([timestampStr, temp, temp2, temp3, tempout])
The file object will always be closed even if an exception is raised. You do not have to close it explicitly. See With statement in Python
I am guessing that your opening a file object in the middle of the script leaves a file open, and then you re-define f after the if __name__ == "__main__. Leaving file objects open can have unpredictable results like the one you're experiencing.
I'm trying to create an uptime command for the bot e.g "the bot has been online for 10 hours 15 minutes 10 seconds"
It works the way as indented up until it hits 12am, I think it might be to do with the calculation but I'm unsure on why it would add -1day when its formatted in hours minutes seconds.
This is what I have at the moment. Any help would be appreciated :)
from datetime import datetime
import os
import time
folder = r"C:\Users\Ryan Mclaughlin\PycharmProjects\Snappingbot-V2\SnappingbotV2\text files"
filename = "uptime.txt"
fp = os.path.join(folder, filename)
with open(fp, "w") as f:
f.writelines(datetime.now().time().strftime('%H:%M:%S')) # on startup of bot write the time in a file
file = open(fp)
startup_time = (file.readline()) # reads the startup time
print(startup_time)
time.sleep(10)
time_now = datetime.now().time().strftime('%H:%M:%S') # finds time now
print(time_now)
FMT = '%H:%M:%S'
tdelta = datetime.strptime(time_now, FMT) - datetime.strptime(startup_time,FMT) # calculates the difference between the startup time and now
print(tdelta)
I am a completely inexperienced A level student trying to get to grips with python to complete an assignment. I have been given a week to complete it - I have very little knowledge of what to do and have no experience with coding - I am truly stuck and will probably seem very stupid to people on his forum.
I have to create a temperature and humidity logger with a raspberry pi and DHT22 sensor. I am to write a script that produces a loop that sleeps for 10 seconds - I will run the script for two days to collect enough data to produce graphs. So far the code I have is this and it's not working - probably for some obvious reasons. The data needs to come out in two columns in a leafpad file. Nothing seems to be happening when I sudo python execute the script - no .txt file has been created in my ls (there is one with just this in it:
indoors
51.58778
-0.15944
But no error message in the LX terminal.. Am I doing something very obviously wrong?
# Assign header details to STRING variables - change manually
txt_studentid = '999'
txt_pi_location = 'indoors'
txt_pi_latitude = '51.58778'
txt_pi_longitude = '-0.15944'
import Adafruit_DHT
pin = 4
sensor = Adafruit_DHT.DHT22
# Import Time module import time
# open file to write
f = open('/home/pi/my_data.txt','w')
f.write(txt_studentid)
f.write('\n')
f.write(txt_pi_location)
f.write('\n')
f.write(txt_pi_latitude)
f.write('\n')
f.write(txt_pi_longitude)
f.write('\n')
f.close()
while True:
# store off the date and time details for this
sample num_month = time.localtime().tm_mon
num_day = time.localtime().tm_mday
num_hour = time.localtime().tm_hour
num_min = time.localtime().tm_min
num_sec = time.localtime().tm_sec
num_humidity, num_temperature = Adafruit_DHT.read_retry(sensor, pin)
txt_month = str(num_month)
txt_day = str(num_day)
txt_hour = str(num_hour)
txt_min = str(num_min)
txt_sec = str(num_sec)
txt_humidity = str(num_humidity)
txt_temperature = str(num_temperature)
f = open('/home/pi/my_data.txt','a')
f.write(txt_month)
f.write(',')
f.write(txt_day)
f.write(',')
f.write(txt_hour)
f.write(',')
f.write(txt_min)
f.write(',')
f.write(txt_sec)
f.write(',')
# write the temperature and humidity to file
f,write(txt_humidity)
f.write(',')
f,write(txt_temperature)
f.write(',')
# write new line
f.write('\n')
# close the file
f.close()
# wait for ten seconds
time.sleep(10)
You definitely want to at least include the file writing in the while loop; or keep track somehow of the readings for later saving.
I've modified your code to help you get started:
import Adafruit_DHT
import time
from datetime import datetime
pin = 4
sensor = Adafruit_DHT.DHT22
# Import Time module import time
# open file to write
f = open('/home/pi/my_data.txt','w')
f.write(txt_studentid)
f.write('\n')
f.write(txt_pi_location)
f.write('\n')
f.write(txt_pi_latitude)
f.write('\n')
f.write(txt_pi_longitude)
f.write('\n')
f.close()
f = open('/home/pi/my_data.txt','a')
begintime = datetime.now()
while True:
# store off the date and time details for this
sample_time = datetime.now()
sample num_month = time.localtime().tm_mon
num_day = time.localtime().tm_mday
num_hour = time.localtime().tm_hour
num_min = time.localtime().tm_min
num_sec = time.localtime().tm_sec
num_humidity, num_temperature = Adafruit_DHT.read_retry(sensor, pin)
txt_month = str(num_month)
txt_day = str(num_day)
txt_hour = str(num_hour)
txt_min = str(num_min)
txt_sec = str(num_sec)
txt_humidity = str(num_humidity)
txt_temperature = str(num_temperature)
f.write(txt_month)
f.write(',')
f.write(txt_day)
f.write(',')
f.write(txt_hour)
f.write(',')
f.write(txt_humidity)
f.write(',')
f.write(num_temperature)
f.write('\n')
time.sleep(10) #sleep for 10 seconds
timedelta = sample_time - begintime
if timedelta.days >= 2:
break
f.close()
I would try setting the timedelta requirement to something like 30 seconds to make sure it works as expected before going up to 2 days. You can do that by changing if timedelta.days >= 2: to if timedelta.seconds >= 30:
I guess you indentation is wrong. You'll get stuck in the while loop and will never write anything to the file. Try indenting everything from num_month = time.localtime().tm_mon to time.sleep(10)