程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python: an alarm clock

編輯:Python

With one 《 Hogwarts : A school history 》 Style of big characters ( Uh , This word doesn't seem to be big ……) The appearance of the title , Boring I have nothing to do , It's starting to work again ~

The program I did before , One is used Tkinter library , One is Pygame, In a word, it has a graphical interface . But as a lazy man , I am naturally lazy ( I know this very well ), This time, , I will come to a simple program without graphical interface .

This is an alarm clock , An alarm clock that can set the time ( Although the operation interface is a little crude , But it doesn't affect its powerful function ).

First , We will program the alarm clock to ring .

Let's create a new file , Suffix is “.pyw”( This can ensure that the program will not pop up a Python Its own window ).

First , Old rules , The first line must be :

#coding:utf-8

then , We need to import the required modules :

import datetime
import pygame
import os
import time
import random
from pynput.keyboard import Key,Listener

Not many modules are required this time , Because I installed them originally , So I'm not sure if they should use pip install . Of course , Use PyCharm Programming can automatically install the uninstalled modules you use .

all_songs=[]
all_songs_dict={}
for root, dirs, names in os.walk("d:/Users/{}/Music".format(os.getlogin())):
for filename in names:
if os.path.join(root, filename)[-4:] == ".mp3" or os.path.join(root, filename)[-4:] == ".ogg":
all_songs.append(os.path.join(root, filename)[os.path.join(root, filename).find("\\") + 1:-4])
all_songs_dict[
os.path.join(root, filename)[os.path.join(root, filename).find("\\") + 1:-4]] = os.path.join(root,
filename).replace(
"\\", "/")

First , We need to get music from the computer . We use it os.walk obtain Music All in folder ogg and mp3 file ( This is because I play music using Pygame, It seems that it only supports the music of these two files ). meanwhile , Through word processing of path string , Extract the music name and store it in the list all_songs, And store it in the dictionary corresponding to the original path all_songs_dict. At this time, the music information stored in these two variables is equivalent to an insurance mechanism , It can ensure that there is an alternate ringtone available when the ringtone file cannot be found ( Of course , If your music folder is empty , Of course it doesn't work ; But I don't think there will be no music in your folder ).

finding = open("alarm_list.txt", "a")
finding.close()
finding = open("alarm_list.txt", "r")
alarm_list_undone = finding.readlines()
finding.close()
alarm_list = []
for i in alarm_list_undone:
alarm_list.append(i.replace("\n", ""))

Of course, our alarm clock time needs to be stored in a file , This can prevent this information from being lost . therefore , We opened a “alarm_list.txt” file ( To prevent the file from nonexistence , We need to open the file in write mode first , This allows you to create when the file does not exist ; At the same time, to prevent this operation, empty the file , We have to write in addition “a” instead of “w”). We will read the contents of the file , And delete the line feed and save it into alarm_list. We don't have to worry about the unrecognized contents in the document , Because the file is written by another editor , That program will ensure that the contents of the file are recognized by this program .

finding = open("dates_one.txt", "a")
finding.close()
finding = open("dates_one.txt", "r")
dates_undone_one = finding.readlines()
finding.close()
finding = open("dates_two.txt", "a")
finding.close()
finding = open("dates_two.txt", "r")
dates_undone_two = finding.readlines()
finding.close()
dates = {}
for i in range(len(dates_undone_one)):
dates[dates_undone_one[i].replace("\n", "")] =eval( dates_undone_two[i].replace("\n", ""))

Empathy , Yes “dates_one.txt” and “dates_two.txt” A similar process is required . Of course , Because there are tables stored in the file , We need to use eval() Function returns its table type . The second difference is that the contents of the two files are stored in a dictionary , Not tables .

finding = open("songs_one.txt", "a")
finding.close()
finding = open("songs_one.txt", "r")
songs_undone_one = finding.readlines()
finding.close()
finding = open("songs_two.txt", "a")
finding.close()
finding = open("songs_two.txt", "r")
songs_undone_two = finding.readlines()
finding.close()
songs = {}
for i in range(len(songs_undone_two)):
try:
open(songs_undone_two[i].replace("\n", ""),"r")
except:
songs_undone_two[i]=all_songs_dict[all_songs[random.randint(0,len(all_songs)-1)]]+"\n"
with open("songs_two.txt", "w")as finding:
finding.writelines(songs_undone_two)
for i in range(len(songs_undone_one)):
songs[songs_undone_one[i].replace("\n", "")] = songs_undone_two[i].replace("\n", "")

In the face of “songs_one.txt” and “songs_two.txt” In the process of , We need to use tables all_songs 了 . To ensure that music exists , It will try to open the file that the path points to . If you can't find the file , It will change the music to all_songs A random music recorded in ( It can be improved here : Add one more if Judge , If the file suffix pointed to by the path is not “.mp3” or “.ogg”, You also have to modify the music . Readers interested in this job can add , I won't give you any more code here —— This is mainly because when I explain my program code, even if I find something unreasonable , As long as it's not a big problem , I don't want to change my habit ).

finding = open("alarm_list.txt", "r")
finder=finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("alarm_list.txt", "w") as finding:
finding.write(finder)
finding = open("dates_one.txt", "r")
finder=finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("dates_one.txt", "w") as finding:
finding.write(finder)
finding = open("dates_two.txt", "r")
finder=finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("dates_two.txt", "w") as finding:
finding.write(finder) finding = open("songs_one.txt", "r")
finder=finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("songs_one.txt", "w") as finding:
finding.write(finder)
finding = open("songs_two.txt", "r")
finder=finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("songs_two.txt", "w") as finding:
finding.write(finder)

I do not know why to delete the program fragment of the alarm clock , There have been some BUG, It will leave a blank line when deleting the alarm clock at the end ( This will cause the program to run incorrectly ). therefore , It is necessary for us to do something about the consequences : Delete the newline character at the end of each file . And this program does such a job .

def delete(i):
global all_songs, all_songs_dict, alarm_list, dates, songs,alarm_list_undone,dates_undone_one,dates_undone_two,songs_undone_one,songs_undone_two
try:
try:
alarm_list_undone.remove(i)
alarm_list[-1] = alarm_list[-1].replace("\n", "")
except:
alarm_list_undone.remove(i + "\n")
except:
if False:
print()
alarm_list.remove(i)
with open("alarm_list.txt", "w") as finding:
finding.writelines(alarm_list_undone)
for j in range(len(songs_undone_one)):
if songs_undone_one[j] == i or songs_undone_one[j] == i + "\n":
songs_undone_one.pop(j)
songs_undone_two.pop(j)
try:
songs_undone_one[-1]=songs_undone_one[-1].replace("\n", "")
songs_undone_two[-1]=songs_undone_two[-1].replace("\n", "")
except:
if False:
print()
songs = {}
for j in range(len(songs_undone_one)):
songs[songs_undone_one[j].replace("\n", "")] = songs_undone_two[j].replace("\n", "")
with open("songs_one.txt", "w") as finding:
finding.writelines(songs_undone_one)
with open("songs_two.txt", "w") as finding:
finding.writelines(songs_undone_two)
for j in range(len(dates_undone_one)):
if dates_undone_one[j] == i or dates_undone_one[j] == i + "\n":
dates_undone_one.pop(j)
dates_undone_two.pop(j)
try:
dates_undone_one[-1]=dates_undone_one[-1].replace("\n", "")
dates_undone_two[-1]=dates_undone_two[-1].replace("\n", "")
except:
if False:
print()
dates = {}
for j in range(len(dates_undone_one)):
dates[dates_undone_one[j].replace("\n", "")] = dates_undone_two[j].replace("\n", "")
with open("dates_one.txt", "w") as finding:
finding.writelines(dates_undone_one)
with open("dates_two.txt", "w") as finding:
finding.writelines(dates_undone_two)

This is what I just mentioned BUG Delete program for . Here's the i It's the time of the alarm clock ( In this program , The alarm clock time is unique , One time only corresponds to one alarm clock ). This program attempts to delete i All corresponding information , however , For alarm clocks at the end of files and tables , It does not deal effectively with . I tried to get him to remove the line break at the end of the previous entry , But clearly something went wrong . I had to add another line of code to make up for the consequences .

def play_it(url):
global Listener
pygame.mixer.init()
t = pygame.mixer.music.load(url)
pygame.mixer.music.play() def on_release(key):
if key == Key.space:
pygame.mixer.music.stop() with Listener(on_release=on_release) as Listener:
Listener.join()

Player , Used to play music when the time is up . Not only does it use Pygame The music of , Also used. Pynput The keyboard monitor , This turns off the music when you press the space ( Of course , Sometimes I may turn off the alarm clock by mistake while typing , But it doesn't matter —— You can set another button that you don't usually use to turn off the alarm clock ).

def alarm():
global all_songs,all_songs_dict,alarm_list,dates,songs
while True:
try:

without doubt , After the code , It follows the core code of the program . But the next paragraph is undoubtedly disappointing :

 e = time.time()
finding = open("alarm_list.txt", "a")
finding.close()
finding = open("alarm_list.txt", "r")
alarm_list_undone = finding.readlines()
finding.close()
alarm_list = []
for i in alarm_list_undone:
alarm_list.append(i.replace("\n", ""))
finding = open("dates_one.txt", "a")
finding.close()
finding = open("dates_one.txt", "r")
dates_undone_one = finding.readlines()
finding.close()
finding = open("dates_two.txt", "a")
finding.close()
finding = open("dates_two.txt", "r")
dates_undone_two = finding.readlines()
finding.close()
dates = {}
for i in range(len(dates_undone_one)):
dates[dates_undone_one[i].replace("\n", "")] = eval(dates_undone_two[i].replace("\n", ""))
finding = open("songs_one.txt", "a")
finding.close()
finding = open("songs_one.txt", "r")
songs_undone_one = finding.readlines()
finding.close()
finding = open("songs_two.txt", "a")
finding.close()
finding = open("songs_two.txt", "r")
songs_undone_two = finding.readlines()
finding.close()
songs = {}
for i in range(len(songs_undone_two)):
try:
open(songs_undone_two[i].replace("\n", ""), "r")
except:
songs_undone_two[i] = all_songs_dict[all_songs[random.randint(0, len(all_songs) - 1)]] + "\n"
with open("songs_two.txt", "w") as finding:
finding.writelines(songs_undone_two)
for i in range(len(songs_undone_one)):
songs[songs_undone_one[i].replace("\n", "")] = songs_undone_two[i].replace("\n", "")
finding = open("alarm_list.txt", "r")
finder = finding.read()
while finder[-1] == "\n":
finder = finder[:-1]
with open("alarm_list.txt", "w") as finding:
finding.write(finder)
finding = open("dates_one.txt", "r")
finder = finding.read()
while finder[-1] == "\n":
finder = finder[:-1]
with open("dates_one.txt", "w") as finding:
finding.write(finder)
finding = open("dates_two.txt", "r")
finder = finding.read()
while finder[-1] == "\n":
finder = finder[:-1]
with open("dates_two.txt", "w") as finding:
finding.write(finder) finding = open("songs_one.txt", "r")
finder = finding.read()
while finder[-1] == "\n":
finder = finder[:-1]
with open("songs_one.txt", "w") as finding:
finding.write(finder)
finding = open("songs_two.txt", "r")
finder = finding.read()
while finder[-1] == "\n":
finder = finder[:-1]
with open("songs_two.txt", "w") as finding:
finding.write(finder)

you 're right , This is the previously stored loaded code . This is to refresh the reading of the file , After all , You will probably change the alarm clock while the program is running .

 for i in alarm_list:
if str(datetime.datetime.now())[11:16] == i:
if time.strftime("%w", time.localtime()) in dates.get(i):
url = songs.get(i)
True_False=int(time.strftime("%Y", time.localtime())) < int(dates.get(i)[-1][4:8]) or (int(time.strftime("%Y", time.localtime())) == int(dates.get(i)[-1][4:8]) and int(time.strftime("%j", time.localtime())) <= int(dates.get(i)[-1][9:]))
if int(time.strftime("%Y", time.localtime())) > int(dates.get(i)[-1][4:8]) or (
int(time.strftime("%Y", time.localtime())) == int(dates.get(i)[-1][4:8]) and int(
time.strftime("%j", time.localtime())) >= int(dates.get(i)[-1][9:])):
delete(i)
if True_False:
play_it(url)
else:
if int(time.strftime("%Y", time.localtime())) > int(dates.get(i)[-1][4:8]) or (
int(time.strftime("%Y", time.localtime())) == int(dates.get(i)[-1][4:8]) and int(
time.strftime("%j", time.localtime())) > int(dates.get(i)[-1][9:])):
delete(i)
if int(time.strftime("%Y", time.localtime())) == int(dates.get(i)[-1][4:8]) and int(time.strftime("%j", time.localtime())) == int(dates.get(i)[-1][9:]) and int(str(datetime.datetime.now())[11:13])*60+int(str(datetime.datetime.now())[14:16]) > int(i[:2])*60+int(i[3:]):
delete(i)

This is the core code you expect ( Although the function is very core , But it is still very simple ) We will traverse the alarm list , Compare the time with the time set by the alarm clock , If this is the time set by an alarm clock , At the same time, the position of the current date in the week ( Let's put it this way , I suddenly found something like “ Monday ” Such words seem to …… There is no general designation ) Also exists in the corresponding table , At the same time, the current date has not exceeded the deadline of the alarm clock , We will ring the bell ( The ringing tone will follow the setting of the alarm clock ). meanwhile , For the alarm clock that has expired , It will be deleted .

such , The procedure of ringing the bell has been preliminarily completed . however , In order that the program does not occupy the process ( This is true of many alarm programs ), We still need to add this code :

 time.sleep(1 - (time.time() - e))
except:
time.sleep(1 - (time.time() - e))

Of course, you have to run the function finally :

alarm()

such , We finished the alarm clock program .

Attach complete code :

#coding:utf-8
import datetime
import pygame
import os
import time
import random
from pynput.keyboard import Key,Listener
all_songs=[]
all_songs_dict={}
for root, dirs, names in os.walk("d:/Users/{}/Music".format(os.getlogin())):
for filename in names:
if os.path.join(root, filename)[-4:] == ".mp3" or os.path.join(root, filename)[-4:] == ".ogg":
all_songs.append(os.path.join(root, filename)[os.path.join(root, filename).find("\\") + 1:-4])
all_songs_dict[
os.path.join(root, filename)[os.path.join(root, filename).find("\\") + 1:-4]] = os.path.join(root,
filename).replace(
"\\", "/") finding = open("alarm_list.txt", "a")
finding.close()
finding = open("alarm_list.txt", "r")
alarm_list_undone = finding.readlines()
finding.close()
alarm_list = []
for i in alarm_list_undone:
alarm_list.append(i.replace("\n", ""))
finding = open("dates_one.txt", "a")
finding.close()
finding = open("dates_one.txt", "r")
dates_undone_one = finding.readlines()
finding.close()
finding = open("dates_two.txt", "a")
finding.close()
finding = open("dates_two.txt", "r")
dates_undone_two = finding.readlines()
finding.close()
dates = {}
for i in range(len(dates_undone_one)):
dates[dates_undone_one[i].replace("\n", "")] =eval( dates_undone_two[i].replace("\n", ""))
finding = open("songs_one.txt", "a")
finding.close()
finding = open("songs_one.txt", "r")
songs_undone_one = finding.readlines()
finding.close()
finding = open("songs_two.txt", "a")
finding.close()
finding = open("songs_two.txt", "r")
songs_undone_two = finding.readlines()
finding.close()
songs = {}
for i in range(len(songs_undone_two)):
try:
open(songs_undone_two[i].replace("\n", ""),"r")
except:
songs_undone_two[i]=all_songs_dict[all_songs[random.randint(0,len(all_songs)-1)]]+"\n"
with open("songs_two.txt", "w")as finding:
finding.writelines(songs_undone_two)
for i in range(len(songs_undone_one)):
songs[songs_undone_one[i].replace("\n", "")] = songs_undone_two[i].replace("\n", "")
finding = open("alarm_list.txt", "r")
finder=finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("alarm_list.txt", "w") as finding:
finding.write(finder)
finding = open("dates_one.txt", "r")
finder=finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("dates_one.txt", "w") as finding:
finding.write(finder)
finding = open("dates_two.txt", "r")
finder=finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("dates_two.txt", "w") as finding:
finding.write(finder) finding = open("songs_one.txt", "r")
finder=finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("songs_one.txt", "w") as finding:
finding.write(finder)
finding = open("songs_two.txt", "r")
finder=finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("songs_two.txt", "w") as finding:
finding.write(finder)
def delete(i):
global all_songs, all_songs_dict, alarm_list, dates, songs,alarm_list_undone,dates_undone_one,dates_undone_two,songs_undone_one,songs_undone_two
try:
try:
alarm_list_undone.remove(i)
alarm_list[-1] = alarm_list[-1].replace("\n", "")
except:
alarm_list_undone.remove(i + "\n")
except:
if False:
print()
alarm_list.remove(i)
with open("alarm_list.txt", "w") as finding:
finding.writelines(alarm_list_undone)
for j in range(len(songs_undone_one)):
if songs_undone_one[j] == i or songs_undone_one[j] == i + "\n":
songs_undone_one.pop(j)
songs_undone_two.pop(j)
try:
songs_undone_one[-1]=songs_undone_one[-1].replace("\n", "")
songs_undone_two[-1]=songs_undone_two[-1].replace("\n", "")
except:
if False:
print()
songs = {}
for j in range(len(songs_undone_one)):
songs[songs_undone_one[j].replace("\n", "")] = songs_undone_two[j].replace("\n", "")
with open("songs_one.txt", "w") as finding:
finding.writelines(songs_undone_one)
with open("songs_two.txt", "w") as finding:
finding.writelines(songs_undone_two)
for j in range(len(dates_undone_one)):
if dates_undone_one[j] == i or dates_undone_one[j] == i + "\n":
dates_undone_one.pop(j)
dates_undone_two.pop(j)
try:
dates_undone_one[-1]=dates_undone_one[-1].replace("\n", "")
dates_undone_two[-1]=dates_undone_two[-1].replace("\n", "")
except:
if False:
print()
dates = {}
for j in range(len(dates_undone_one)):
dates[dates_undone_one[j].replace("\n", "")] = dates_undone_two[j].replace("\n", "")
with open("dates_one.txt", "w") as finding:
finding.writelines(dates_undone_one)
with open("dates_two.txt", "w") as finding:
finding.writelines(dates_undone_two)
def play_it(url):
global Listener
pygame.mixer.init()
t = pygame.mixer.music.load(url)
pygame.mixer.music.play() def on_release(key):
if key == Key.space:
pygame.mixer.music.stop() with Listener(on_release=on_release) as Listener:
Listener.join()
def alarm():
global all_songs,all_songs_dict,alarm_list,dates,songs
while True:
try:
e = time.time()
finding = open("alarm_list.txt", "a")
finding.close()
finding = open("alarm_list.txt", "r")
alarm_list_undone = finding.readlines()
finding.close()
alarm_list = []
for i in alarm_list_undone:
alarm_list.append(i.replace("\n", ""))
finding = open("dates_one.txt", "a")
finding.close()
finding = open("dates_one.txt", "r")
dates_undone_one = finding.readlines()
finding.close()
finding = open("dates_two.txt", "a")
finding.close()
finding = open("dates_two.txt", "r")
dates_undone_two = finding.readlines()
finding.close()
dates = {}
for i in range(len(dates_undone_one)):
dates[dates_undone_one[i].replace("\n", "")] = eval(dates_undone_two[i].replace("\n", ""))
finding = open("songs_one.txt", "a")
finding.close()
finding = open("songs_one.txt", "r")
songs_undone_one = finding.readlines()
finding.close()
finding = open("songs_two.txt", "a")
finding.close()
finding = open("songs_two.txt", "r")
songs_undone_two = finding.readlines()
finding.close()
songs = {}
for i in range(len(songs_undone_two)):
try:
open(songs_undone_two[i].replace("\n", ""), "r")
except:
songs_undone_two[i] = all_songs_dict[all_songs[random.randint(0, len(all_songs) - 1)]] + "\n"
with open("songs_two.txt", "w") as finding:
finding.writelines(songs_undone_two)
for i in range(len(songs_undone_one)):
songs[songs_undone_one[i].replace("\n", "")] = songs_undone_two[i].replace("\n", "")
finding = open("alarm_list.txt", "r")
finder = finding.read()
while finder[-1] == "\n":
finder = finder[:-1]
with open("alarm_list.txt", "w") as finding:
finding.write(finder)
finding = open("dates_one.txt", "r")
finder = finding.read()
while finder[-1] == "\n":
finder = finder[:-1]
with open("dates_one.txt", "w") as finding:
finding.write(finder)
finding = open("dates_two.txt", "r")
finder = finding.read()
while finder[-1] == "\n":
finder = finder[:-1]
with open("dates_two.txt", "w") as finding:
finding.write(finder) finding = open("songs_one.txt", "r")
finder = finding.read()
while finder[-1] == "\n":
finder = finder[:-1]
with open("songs_one.txt", "w") as finding:
finding.write(finder)
finding = open("songs_two.txt", "r")
finder = finding.read()
while finder[-1] == "\n":
finder = finder[:-1]
with open("songs_two.txt", "w") as finding:
finding.write(finder)
for i in alarm_list:
if str(datetime.datetime.now())[11:16] == i:
if time.strftime("%w", time.localtime()) in dates.get(i):
url = songs.get(i)
True_False=int(time.strftime("%Y", time.localtime())) < int(dates.get(i)[-1][4:8]) or (int(time.strftime("%Y", time.localtime())) == int(dates.get(i)[-1][4:8]) and int(time.strftime("%j", time.localtime())) <= int(dates.get(i)[-1][9:]))
if int(time.strftime("%Y", time.localtime())) > int(dates.get(i)[-1][4:8]) or (
int(time.strftime("%Y", time.localtime())) == int(dates.get(i)[-1][4:8]) and int(
time.strftime("%j", time.localtime())) >= int(dates.get(i)[-1][9:])):
delete(i)
if True_False:
play_it(url)
else:
if int(time.strftime("%Y", time.localtime())) > int(dates.get(i)[-1][4:8]) or (
int(time.strftime("%Y", time.localtime())) == int(dates.get(i)[-1][4:8]) and int(
time.strftime("%j", time.localtime())) > int(dates.get(i)[-1][9:])):
delete(i)
if int(time.strftime("%Y", time.localtime())) == int(dates.get(i)[-1][4:8]) and int(time.strftime("%j", time.localtime())) == int(dates.get(i)[-1][9:]) and int(str(datetime.datetime.now())[11:13])*60+int(str(datetime.datetime.now())[14:16]) > int(i[:2])*60+int(i[3:]):
delete(i)
time.sleep(1 - (time.time() - e))
except:
time.sleep(1 - (time.time() - e)) print(all_songs)
print(all_songs_dict)
print(alarm_list)
print(dates)
print(songs)
alarm()

Are you wondering : How do we set the alarm clock ? What follows , Let's settle this matter .

The easiest way , Of course, manually input the alarm clock into the file .“alarm_list.txt” You need to enter the time of the alarm clock in , Format “00:00”;“dates_one.txt” and “songs_one.txt” In fact, this content is stored in .“songs_two.txt” Is the path of music , It's okay ; most important of all “dates_two.txt”. Let's take an example .“['1', '2', '3', '4', '5', 'kill9999&99']”, What's the meaning of this? ?“1”“2”“3”“4”“5” The week when the bell rings , among “0” On behalf of the Sunday ,“1” On behalf of the Monday , And so on .“kill9999&99” Is the alarm clock due date , Or the expiration date ,“9999” is ,“99” Is the number of days in the year ,“kill9999&99” Meaning for “ Valid until 9999 Year of 4 month 9 Japan ”, Here we can simply and rudely think of it as never stopping ( Because generally speaking , This program will never run until that day ). in other words “['1', '2', '3', '4', '5', 'kill9999&99']” It means , The bell rings every weekday , Always effective .

Of course , It would actually be more tedious , So I went through a series of more tedious steps , Made an alarm clock setting program ( Only the code is given here , Because it mainly contains simple but repeated contents ):

#coding:utf-8
import random
import os
import datetime
import time
try:
all_songs = []
all_songs_dict = {}
for root, dirs, names in os.walk("d:/Users/{}/Music".format(os.getlogin())):
for filename in names:
if os.path.join(root, filename)[-4:] == ".mp3" or os.path.join(root, filename)[-4:] == ".ogg":
all_songs.append(os.path.join(root, filename)[os.path.join(root, filename).find("\\") + 1:-4])
all_songs_dict[
os.path.join(root, filename)[os.path.join(root, filename).find("\\") + 1:-4]] = os.path.join(root,
filename).replace(
"\\", "/")
finding = open("alarm_list.txt", "a")
finding.close()
finding = open("alarm_list.txt", "r")
alarm_list_undone = finding.readlines()
finding.close()
alarm_list = []
for i in alarm_list_undone:
alarm_list.append(i.replace("\n", ""))
finding = open("dates_one.txt", "a")
finding.close()
finding = open("dates_one.txt", "r")
dates_undone_one = finding.readlines()
finding.close()
finding = open("dates_two.txt", "a")
finding.close()
finding = open("dates_two.txt", "r")
dates_undone_two = finding.readlines()
finding.close()
dates = {}
for i in range(len(dates_undone_one)):
dates[dates_undone_one[i].replace("\n", "")] = eval(dates_undone_two[i].replace("\n", ""))
finding = open("songs_one.txt", "a")
finding.close()
finding = open("songs_one.txt", "r")
songs_undone_one = finding.readlines()
finding.close()
finding = open("songs_two.txt", "a")
finding.close()
finding = open("songs_two.txt", "r")
songs_undone_two = finding.readlines()
finding.close()
songs = {}
for i in range(len(songs_undone_two)):
try:
open(songs_undone_two[i].replace("\n", ""), "r")
except:
songs_undone_two[i] = all_songs_dict[all_songs[random.randint(0, len(all_songs) - 1)]] + "\n"
with open("songs_two.txt", "w") as finding:
finding.writelines(songs_undone_two)
for i in range(len(songs_undone_one)):
songs[songs_undone_one[i].replace("\n", "")] = songs_undone_two[i].replace("\n", "")
finding = open("alarm_list.txt", "r")
finder = finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("alarm_list.txt", "w") as finding:
finding.write(finder)
finding = open("dates_one.txt", "r")
finder = finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("dates_one.txt", "w") as finding:
finding.write(finder)
finding = open("dates_two.txt", "r")
finder = finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("dates_two.txt", "w") as finding:
finding.write(finder) finding = open("songs_one.txt", "r")
finder = finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("songs_one.txt", "w") as finding:
finding.write(finder)
finding = open("songs_two.txt", "r")
finder = finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("songs_two.txt", "w") as finding:
finding.write(finder)
print(" Please select service :")
print()
print("1: New alarm clock ")
print("2: Manage alarm clock ")
print()
top = input(" Your choice :")
if top == "1":
print()
set_time = input(" Please enter the alarm time ( Format :00:00):")
have_it = False
for i in alarm_list:
if i == set_time:
have_it = True
try:
alarm_list_undone[-1] += "\n"
except:
if False:
print()
alarm_list_undone.append(set_time)
alarm_list = []
for i in alarm_list_undone:
alarm_list.append(i.replace("\n", ""))
with open("alarm_list.txt", "w") as finding:
finding.writelines(alarm_list_undone)
print()
print(" Please select the number of rings :")
print()
print(" 1: Only once ")
print(" 2: Every day ")
print(" 3: Working day ")
print(" 4: Customize ")
print()
set_date = input(" Your choice :")
if set_date == "1":
if int(set_time[:set_time.find(":")]) * 60 + int(set_time[set_time.find(":") + 1:]) <= int(
str(datetime.datetime.now())[11:16][:str(datetime.datetime.now())[11:16].find(":")]) * 60 + int(
str(datetime.datetime.now())[11:16][str(datetime.datetime.now())[11:16].find(":") + 1:]):
try:
dates_undone_one[-1] += "\n"
except:
if False:
print()
dates_undone_one.append(set_time)
try:
dates_undone_two[-1] += "\n"
except:
if False:
print()
dates_undone_two.append(str([(datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%w"),
"kill{}&{}".format(
(datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y"),
(datetime.datetime.now() + datetime.timedelta(days=1)).strftime(
"%j"))]))
else:
try:
dates_undone_one[-1] += "\n"
except:
if False:
print()
dates_undone_one.append(set_time)
try:
dates_undone_two[-1] += "\n"
except:
if False:
print()
dates_undone_two.append(str([(datetime.datetime.now()).strftime("%w"),
"kill{}&{}".format((datetime.datetime.now()).strftime("%Y"),
(datetime.datetime.now()).strftime("%j"))])) dates = {}
for i in range(len(dates_undone_one)):
dates[dates_undone_one[i].replace("\n", "")] = eval(dates_undone_two[i].replace("\n", ""))
with open("dates_one.txt", "w") as finding:
finding.writelines(dates_undone_one)
with open("dates_two.txt", "w") as finding:
finding.writelines(dates_undone_two)
if set_date == "2":
try:
dates_undone_one[-1] += "\n"
except:
if False:
print()
dates_undone_one.append(set_time)
try:
dates_undone_two[-1] += "\n"
except:
if False:
print()
dates_undone_two.append(str(["1", "2", "3", "4", "5", "6", "0", "kill9999&99"]))
dates = {}
for i in range(len(dates_undone_one)):
dates[dates_undone_one[i].replace("\n", "")] = eval(dates_undone_two[i].replace("\n", ""))
with open("dates_one.txt", "w") as finding:
finding.writelines(dates_undone_one)
with open("dates_two.txt", "w") as finding:
finding.writelines(dates_undone_two)
if set_date == "3":
try:
dates_undone_one[-1] += "\n"
except:
if False:
print()
dates_undone_one.append(set_time)
try:
dates_undone_two[-1] += "\n"
except:
if False:
print()
dates_undone_two.append(str(["1", "2", "3", "4", "5", "kill9999&99"]))
dates = {}
for i in range(len(dates_undone_one)):
dates[dates_undone_one[i].replace("\n", "")] = eval(dates_undone_two[i].replace("\n", ""))
with open("dates_one.txt", "w") as finding:
finding.writelines(dates_undone_one)
with open("dates_two.txt", "w") as finding:
finding.writelines(dates_undone_two)
if set_date == "4":
list_one = []
math_to_week = {0: " Sunday ", 1: " Monday ", 2: " Tuesday ", 3: " Wednesday ", 4: " Thursday ", 5: " Friday ", 6: " Saturday "}
for i in range(7):
print()
yes_no = input(" {} Do you want to ring ( It's input “1”, No input “0”):".format(math_to_week.get(i)))
if yes_no == "1":
list_one.append(str(i))
list_one.append("kill9999&99")
try:
dates_undone_one[-1] += "\n"
except:
if False:
print()
dates_undone_one.append(set_time)
try:
dates_undone_two[-1] += "\n"
except:
if False:
print()
dates_undone_two.append(str(list_one))
dates = {}
for i in range(len(dates_undone_one)):
dates[dates_undone_one[i].replace("\n", "")] = eval(dates_undone_two[i].replace("\n", ""))
with open("dates_one.txt", "w") as finding:
finding.writelines(dates_undone_one)
with open("dates_two.txt", "w") as finding:
finding.writelines(dates_undone_two)
print()
print(" Please select ringing tone :")
print()
num = 0
for i in all_songs:
num += 1
print(" " + str(num) + ":《" + i + "》")
num += 1
print(" " + str(num) + ": Optional ")
print()
set_song = input(" Your choice :")
if not set_song == str(num):
song = all_songs_dict[all_songs[int(set_song) - 1]]
else:
print()
song = input(" Please enter the path :")
try:
songs_undone_one[-1] += "\n"
except:
if False:
print()
songs_undone_one.append(set_time)
try:
songs_undone_two[-1] += "\n"
except:
if False:
print()
songs_undone_two.append(song)
songs = {}
for i in range(len(songs_undone_two)):
try:
open(songs_undone_two[i].replace("\n", ""), "r")
except:
songs_undone_two[i] = all_songs_dict[all_songs[random.randint(0, len(all_songs) - 1)]] + "\n"
with open("songs_two.txt", "w") as finding:
finding.writelines(songs_undone_two)
for i in range(len(songs_undone_one)):
songs[songs_undone_one[i].replace("\n", "")] = songs_undone_two[i].replace("\n", "")
with open("songs_one.txt", "w") as finding:
finding.writelines(songs_undone_one)
with open("songs_two.txt", "w") as finding:
finding.writelines(songs_undone_two)
else:
print()
print(" Please select the alarm clock to delete :")
print()
for i in range(len(alarm_list)):
if dates[alarm_list[i]][-1] != "kill9999&99":
date_type = " Only once "
elif dates[alarm_list[i]] == ["1", "2", "3", "4", "5", "6", "0", "kill9999&99"]:
date_type = " Every day "
elif dates[alarm_list[i]] == ["1", "2", "3", "4", "5", "kill9999&99"]:
date_type = " Working day "
else:
date_type = " Customize "
print(" {}: Time :{}; Number of rings :{}; music :《{}》;".format(i + 1, alarm_list[i], date_type, songs[alarm_list[i]][
songs[alarm_list[i]].rfind(
"/") + 1:songs[
alarm_list[i]].rfind(".")]))
print()
delete = int(input(" Your choice :"))
alarm_list_undone.pop(delete - 1)
dates_undone_one.pop(delete - 1)
dates_undone_two.pop(delete - 1)
songs_undone_one.pop(delete - 1)
songs_undone_two.pop(delete - 1)
with open("alarm_list.txt", "w") as finding:
finding.writelines(alarm_list_undone)
with open("songs_one.txt", "w") as finding:
finding.writelines(songs_undone_one)
with open("songs_two.txt", "w") as finding:
finding.writelines(songs_undone_two)
with open("dates_one.txt", "w") as finding:
finding.writelines(dates_undone_one)
with open("dates_two.txt", "w") as finding:
finding.writelines(dates_undone_two)
finding = open("alarm_list.txt", "a")
finding.close()
finding = open("alarm_list.txt", "r")
alarm_list_undone = finding.readlines()
finding.close()
alarm_list = []
for i in alarm_list_undone:
alarm_list.append(i.replace("\n", ""))
finding = open("dates_one.txt", "a")
finding.close()
finding = open("dates_one.txt", "r")
dates_undone_one = finding.readlines()
finding.close()
finding = open("dates_two.txt", "a")
finding.close()
finding = open("dates_two.txt", "r")
dates_undone_two = finding.readlines()
finding.close()
dates = {}
for i in range(len(dates_undone_one)):
dates[dates_undone_one[i].replace("\n", "")] = eval(dates_undone_two[i].replace("\n", ""))
finding = open("songs_one.txt", "a")
finding.close()
finding = open("songs_one.txt", "r")
songs_undone_one = finding.readlines()
finding.close()
finding = open("songs_two.txt", "a")
finding.close()
finding = open("songs_two.txt", "r")
songs_undone_two = finding.readlines()
finding.close()
songs = {}
for i in range(len(songs_undone_two)):
try:
open(songs_undone_two[i].replace("\n", ""), "r")
except:
songs_undone_two[i] = all_songs_dict[all_songs[random.randint(0, len(all_songs) - 1)]] + "\n"
with open("songs_two.txt", "w") as finding:
finding.writelines(songs_undone_two)
for i in range(len(songs_undone_one)):
songs[songs_undone_one[i].replace("\n", "")] = songs_undone_two[i].replace("\n", "")
finding = open("alarm_list.txt", "r")
finder = finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("alarm_list.txt", "w") as finding:
finding.write(finder)
finding = open("dates_one.txt", "r")
finder = finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("dates_one.txt", "w") as finding:
finding.write(finder)
finding = open("dates_two.txt", "r")
finder = finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("dates_two.txt", "w") as finding:
finding.write(finder) finding = open("songs_one.txt", "r")
finder = finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("songs_one.txt", "w") as finding:
finding.write(finder)
finding = open("songs_two.txt", "r")
finder = finding.read()
try:
while finder[-1] == "\n":
finder = finder[:-1]
except:
while False:
print()
with open("songs_two.txt", "w") as finding:
finding.write(finder)
except:
while False:
print()

This program cannot be pyw file , And must be py( Because it requires input and output ). We need to put it in the same folder as the ring program just now , And create a shortcut for each of the two programs . then , We're going to put the ring program into “ start-up ” Folder ( stay C disc , The name is “StartUp”. Its path on my computer is “C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp”, The path may be slightly different on different computers , But search always finds it ). And another one. , A shortcut to this setup program , You can put it on the table , Easy to open the program .

Python: More about an alarm clock

  1. use UILocalNotification Realize an alarm clock (Swift)

    The previous project needs to implement an alarm clock ,github After searching for a long time, I found that the code is very old , So I'm going to write one by myself , I've just been studying Swift, Just use Swift Wrote a demo Put it here :https://github.com/P ...

  2. python—— Timed alarm clock explanation

    I wrote my own alarm clock , Play only wav Format audio . import time import sys soundFile = 'sound.wav' not_executed = 1 def soundStar ...

  3. python A place to pay attention to

    https://www.zhihu.com/question/25874136 class test: l=[] def init(self): self.l=['1','2','7'] a1=tes ...

  4. Android Get an alarm clock in a third party

    Collecting alarm information Alarm time , Alarm notes The point where the alarm causes the system to change : 1. Send Notification ( On time alarm can be set not to send ) 2. Play audio Alarm information structure ClockInfo{ S ...

  5. Elegant python - A simple server

    python It has the ability to set up a single server to listen on the port , Using the standard library wsgiref Just go . from wsgiref.simple_server import make_server def simple_a ...

  6. Parallel Python—— A simple distributed computing system

    How to build a high-speed distributed computing platform ?Parallel python This purpose . Parallel Python(http://www.parallelpython.com/content/view/15/3 ...

  7. Python A command is on http Download Server ( You can share files within the LAN )

    Prerequisite :windows Installation on system python If you want to put the D:\asdm As a directory to provide downloads , open cmd then cd Command to enter the directory :cd D:\asdm, And then execute Python -m SimpleHTTPS ...

  8. Python—— The creation and application of a simple class

    1. Create a class , Set properties and set default values for properties , Set the method and access the properties of the class : 2. Create multiple instances using classes , And two ways to call the methods of the class : 3. Function that sets the update property , And update the properties of the instance . class dog(object): ...

  9. Study python One month inventory

    1, I saw 30 Multiple videos , It's some basic operations . A rough understanding of the grammar , function , loop , Regular expression , Type all the video content into the text : 2, I saw 100 Page book , The exercises are not very good , It's going very slowly . The fifth chapter 10 I didn't do any questions later : 3, see C++ The book of , somewhat ...

  10. python A simple Packaging example

    Recently I wrote some tools , It is troublesome to think of sharing with colleagues , And you need to open it every time you use it pycharm These tools , It's a lot of trouble , So I thought of packing , There are some examples on the Internet , After doing so, I groped for a long time , Just record it , For a rainy day . Main reference :htt ...

Random recommendation

  1. Full deployment CentOS7.2+OpenStack+kvm Cloud platform environment (3)-- Specify fixed... For the virtual machine ip

    Before in the test environment (centos7.2) The upper part has been deployed. openstack Cloud platform ( Full deployment CentOS7.2+OpenStack+kvm Cloud platform environment (1)-- Basic environment construction ),openstack stay neutron networking ...

  2. Let you forget Flash Of 15 Wonderful HTML5 game

    HTML5 Game development is a hot topic , Developers and designers have often talked about . Although it can't be replaced quickly Flash The status of , however HTML5 With its openness and powerful programming ability , replace Flash It's an inevitable trend . You'll see ...

  3. stay Kibana Format fields on , The better is dashboard On display

    One . Why format ? And then the previous article - utilize ELK Systems analysis Nginx Log and visualize the data . Here is http Access logs , There is a field ,bytes Bytes transmitted , Here's the picture : This request is selected in the green box ...

  4. MornUI Source reading notes

    1. label Of mouseChildren The attribute is true, but label You don't need to listen textfield Of any event , My guess is to give TextInput, TextArea With , Because the latter two need to be monitored ...

  5. Easy configuration java development environment

    1. download java Develop common IDE(Integrated Development Environment)--eclipse.http://www.eclipse.org/downloads/ 2. download ...

  6. NET Core Micro service road : be based on Ocelot Of API gateway Relay Realization --RPC piece

    Preface We all know ,API A gateway is a gateway program that works on the application layer , Why is it designed this way , Rather than having the gateway program work directly at the transport layer . Or the network layer or something lower ? Let's look at it briefly TCP/IP The five-tier model .     ( picture ...

  7. ( character string Array recursive Double pointer ) leetcode 344. Reverse String

    Write a function that reverses a string. The input string is given as an array of characters char[]. ...

  8. 【 Detailed record MySql A complete collection of problems 】 Two 、 Install and crack Navicat

    Navicat for MySql 11.1.13 Enterprise Edition Download address : link :https://pan.baidu.com/s/1N3ZQXNyx-W8D4AsuZdsMug password :x0rd The second is N ...

  9. build yum The server

    One .yum Server side configuration 1. install FTP Software #yum install vsftpd #service vsftpd start#chkconfig --add vsftpd#chkconfig vsftp ...

  10. linux System input method settings

    The first is to install the Chinese input method , Take Sogou as an example . 2 from system settings Get into language support , stay keyboard input method system You can't see your own installation in ...


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved