Python:一個鬧鐘

2022-06-28 15:02:59

隨著一個《霍格沃茨:一段校史》風格的大字(呃,這字好像並不大……)標題的出現,無聊的我沒事幹,又開始整活了~

之前我做的程式,一個使用了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」,不同電腦上路徑可能稍有不同,但搜尋總是能找到的)。而另一個,這個設定程式的快捷方式,你可以放在桌面,方便開啟程式。