自作タイマー
自作タイマー
Pythonで自作したCLIのタイマー
自作プログラム
HH:MM:SSでタイマーがセットできる
各項目は省略可能
pで設定すると45分、rで設定すると5分、rrrrで設定すると15分でタイマーがスタートする
ポドローモタイマー
AM/PM HH:MMでアラーム機能
絶対改善の余地あり
code:python
import re
from datetime import datetime, timedelta
import asyncio
from playsound import playsound
typeamount = 3
# 音声ファイルのパスを指定
audio_file = R"D:\Project\Project_Python\hour.wav"
#アラーム処理
async def Alarm():
playsound(audio_file)
def convert_to_sec(sec: int, min: int = 0, hour: int = 0) -> int:
return sec + min*60 + hour*60*60
def length_amount(list: list):
listtype = len(list)
if listtype < typeamount:
for i in range(typeamount-listtype):
list.insert(0, 0)
elif listtype > typeamount:
del list0:listtype-typeamount
return list
def when_the_time(input_str) -> int:
pattern = r"^(am|pm)\s?(\d{1,2}):(\d{2})$"
match = re.fullmatch(pattern, input_str, re.IGNORECASE)
if not match:
return None
period = match.group(1).lower()
hour = int(match.group(2))
minute = int(match.group(3))
if period == "pm" and hour != 12:
hour += 12
elif period == "am" and hour == 12:
hour = 0
if hour > 23 or minute > 59:
return None
now = datetime.now()
target = now.replace(hour=hour, minute=minute, second=0, microsecond=0)
if target <= now:
target += timedelta(days=1)
diff = target - now
return int(diff.total_seconds())
def isListDigit(list: list):
for i in list:
if not i.isdigit():
return False
return True
async def countup(sec):
try:
count = 0
while count != sec:
count += 1
print(f"{count}/{sec}")
await asyncio.sleep(1)
except Exception as e:
print(f"countup error: {e}")
async def timer(sec: int):
try:
print(f"After {sec} sec.")
asyncio.create_task(countup(sec))
await asyncio.sleep(sec)
print("Ring!")
asyncio.create_task(Alarm())
return
except Exception as e:
print(f"timer error: {e}")
return
async def main():
while True:
try:
await asyncio.sleep(0.1)
time_input = await asyncio.to_thread(input, "")
if time_input.lower() == "exit":
print("Good bye.")
break
if re.fullmatch(r"^(am|AM|pm|PM)\s?\d{1,2}:\d{2}$", time_input):
seconds = when_the_time(time_input)
asyncio.create_task(timer(seconds))
continue
time_parts = time_input.split(":")
if isListDigit(time_parts):
time_parts = int(i) for i in time_parts
time_parts = length_amount(time_parts)
seconds:int = convert_to_sec(time_parts-1, time_parts-2, time_parts-3)
asyncio.create_task(timer(seconds))
elif time_parts0 == "p":
asyncio.create_task(timer(25*60))
elif time_parts0 == "r":
asyncio.create_task(timer(5*60))
elif time_parts0 == "rrrr":
asyncio.create_task(timer(15*60))
except Exception as e:
print(f"error: {e}")
break
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("Good bye.")
except RuntimeError as e:
if "Event loop is closed" not in str(e):
raise