编程语言
首页 > 编程语言> > Python:一个闹钟

Python:一个闹钟

作者:互联网

随着一个《霍格沃茨:一段校史》风格的大字(呃,这字好像并不大……)标题的出现,无聊的我没事干,又开始整活了~

之前我做的程序,一个使用了Tkinter库,一个则是Pygame,总之都是带有图形化的界面的。但作为一个懒汉,我自然能懒必懒(这点我非常有自知之明),这次,我就来一个简单朴素的没有图形界面的程序。

这是一个闹钟,一个可以设定时间的闹钟(虽然操作的界面有点简陋,但丝毫不影响它的强大功能)。

首先,我们要编闹钟的响铃程序。

我们先新建一个文件,后缀是“.pyw”(这样可以保证程序运行的时候不会弹出一个Python自带的窗口)。

首先,老规矩,第一行一定是:

#coding:utf-8

然后,我们要导入所需的模块:

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

本次所需的模块不多,由于都是我原先安装好的,所以我也并不确定它们是否要用pip安装。当然,使用PyCharm进行编程可以自动为你安装你使用到的未安装的模块。

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(
                "\\", "/")

首先,我们需要获取电脑中的音乐。我们用os.walk获取Music文件夹中的所有ogg和mp3文件(这是由于我播放音乐使用的是Pygame,它似乎只支持这两种文件的音乐)。同时,通过对路径字符串的文字处理,提取出音乐名称存储入列表all_songs,并将其和原先的路径对应存入字典all_songs_dict。这时存入这两个变量中的音乐信息相当于一种保险机制,可以确保在找不到铃声文件时有备用铃声可以使用(当然,如果你的音乐文件夹是空的,这当然没用;但我不认为你的文件夹中会没有音乐)。

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", ""))

我们的闹钟时间当然需要存储在某个文件中,这样才能防止这个信息丢失。于是,我们打开了一个“alarm_list.txt”文件(为防止文件不存在,我们需要先用写入的模式打开一次文件,这样可以在文件不存在时创建;同时为防止这个操作清空文件,我们必须用追加写的“a”而不是“w”)。我们会读取文件中的内容,并删除换行后存入alarm_list。我们不必忧心文件中有无法识别的内容,因为文件是通过另一个编辑程序写入的,那个程序会保证文件内容是这个程序所能识别的。

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", ""))

同理,对“dates_one.txt”和“dates_two.txt”也需要类似的处理。当然,因为文件中存储有表格,我们有必要用eval()函数回复它的表格类型。第二个不同在于这两个文件的内容会被存入一个字典,而不是表格。

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", "")

在对“songs_one.txt”和“songs_two.txt”的处理中,我们就需要用到表格all_songs了。为保证音乐都存在,它会尝试打开路径所指向的文件。如果找不到文件,它会将音乐修改为all_songs中所记录的随机一个音乐(在这里可以进行改善:加一个if判断,如果路径指向的文件后缀不是“.mp3”或“.ogg”,则也要修改音乐。这个工作感兴趣的读者可以自行加上,在此我不再给出代码——这主要是由于我在解释我的程序代码时即使发现了不合理之处,只要不是大问题,就也不愿再行修改的习惯)。

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)

我的删除闹钟的程序片段不知为何,一直有一些BUG,会在删除处于结尾的闹钟时留下空行(这会导致程序运行出错)。于是,我们很有必要对其的后果作出一些挽回:将每一个文件结尾的换行符删除。而这个程序就是进行了这样一个工作。

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)

这就是刚刚提到的有BUG的删除程序。这里输入的i是闹钟的时间(在这个程序中,闹钟时间具有唯一性,一个时间只对应一个闹钟)。这个程序试图删除i所对应的所有信息,但是,对于位于文件和表格结尾的闹钟,它不能有效处理。我试图使他删除上一个条末尾的换行符,但显然出现了某种错误。我因此不得不另加一行代码来弥补它的后果。

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()

播放程序,用于在时间到时播放音乐。这里不仅使用了Pygame的音乐播放,还使用了Pynput的键盘监听,这样可以在按下空格时关闭音乐(当然,有时候在打字时也许会误关闹钟,但这无关紧要——你完全可以设置另一个不常用的键来关闭闹钟)。

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))

当然最后得运行函数:

alarm()

这样,我们就把闹钟的程序完成了。

附上完整代码:

#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()

你是否疑惑:我们如何设置闹钟?这后面的内容,我们就来解决这一件事。

最简单的办法,当然是将闹钟手动输入到文件中。“alarm_list.txt”中需要输入的是闹钟的时间,格式“00:00”;“dates_one.txt”和“songs_one.txt”中储存的其实也是这一内容。“songs_two.txt”中是音乐的路径,这个也没问题;最重要的是“dates_two.txt”。我们不妨举个例子。“['1', '2', '3', '4', '5', 'kill9999&99']”,这是什么意思?“1”“2”“3”“4”“5”指响铃的星期,其中“0”代表周日,“1”代表周一,后面以此类推。“kill9999&99”是闹钟截至日期,或者说有效期,“9999”是年,“99”是在这年中的天数,“kill9999&99”意为“有效期至公元9999年的4月9日”,在这里我们可以简单粗暴的认为是永不停止(因为一般来说,这个程序是绝对不会运行到那一天的)。也就是说“['1', '2', '3', '4', '5', 'kill9999&99']”的意思大概就是,每周工作日响铃,永远有效。

当然,这么做实际会比较繁琐,因此我经过一连串更繁琐的步骤后,制作了一个闹钟的设置程序(在此只给出代码,因为它里面主要都是些简单却反复的内容):

 

#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("请选择服务:")
    print()
    print("1:新建闹钟")
    print("2:管理闹钟")
    print()
    top = input("你的选择:")
    if top == "1":
        print()
        set_time = input(" 请输入闹钟时间(格式: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(" 请选择响铃次数:")
        print()
        print(" 1:仅一次")
        print(" 2:每天")
        print(" 3:工作日")
        print(" 4:自定义")
        print()
        set_date = input(" 你的选择:")
        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: "星期日", 1: "星期一", 2: "星期二", 3: "星期三", 4: "星期四", 5: "星期五", 6: "星期六"}
            for i in range(7):
                print()
                yes_no = input(" {}是否响铃(是输入“1”,否输入“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(" 请选择铃声:")
        print()
        num = 0
        for i in all_songs:
            num += 1
            print(" " + str(num) + ":《" + i + "》")
        num += 1
        print(" " + str(num) + ":自选")
        print()
        set_song = input(" 你的选择:")
        if not set_song == str(num):
            song = all_songs_dict[all_songs[int(set_song) - 1]]
        else:
            print()
            song = input(" 请输入路径:")
        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(" 请选择需要删除的闹钟:")
        print()
        for i in range(len(alarm_list)):
            if dates[alarm_list[i]][-1] != "kill9999&99":
                date_type = "仅一次"
            elif dates[alarm_list[i]] == ["1", "2", "3", "4", "5", "6", "0", "kill9999&99"]:
                date_type = "每天"
            elif dates[alarm_list[i]] == ["1", "2", "3", "4", "5", "kill9999&99"]:
                date_type = "工作日"
            else:
                date_type = "自定义"
            print(" {}:时间:{};响铃次数:{};音乐:《{}》;".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(" 你的选择:"))
        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()

 

这个程序不能是pyw文件,而必须是py(因为它需要输入与输出)。我们需要将其和刚刚的响铃程序放在同一个文件夹中,并对两个程序分别创建一个快捷方式。然后,我们要将响铃程序放入“启动”文件夹(在C盘,名称叫“StartUp”。它在我的电脑上路径为“C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp”,不同电脑上路径可能稍有不同,但搜索总是能找到的)。而另一个,这个设置程序的快捷方式,你可以放在桌面,方便打开程序。

标签:dates,Python,一个,undone,闹钟,finding,txt,finder,songs
来源: https://www.cnblogs.com/godforever/p/16418496.html