【Python】カウントダウンタイマーを作成する

Pythonでカウントダウンタイマーのコンソールアプリケーションを作成しました。
時間(分)を指定し、指定時間後にmp3ファイルを再生します。
1分後にsound.mp3を再生するにはcountdown_timer.pyの引数に1とsound.mp3を指定します。

1python countdown_timer.py 1 sound.mp3
 1import argparse
 2import time
 3import sys
 4import os
 5from mutagen.mp3 import MP3
 6import pygame
 7
 8
 9class CountDownTimer:
10
11    def __init__(self, minutes, mp3_filepath):
12        self.minutes = minutes
13        self.seconds = 0
14        self.mp3_file_path = mp3_filepath
15
16    def validate_arg_minutes(self):
17        """引数の時間をチェック"""
18        if self.minutes < 0:
19            print('時間には0以上の整数を入力してください。')
20            return False
21        return True
22
23    def validate_arg_mp3_filepath(self):
24        """引数のmp3ファイルをチェック"""
25        if self.mp3_file_path == '':
26            print('mp3ファイルのパスを入力してください')
27            return False
28        if not os.path.exists(self.mp3_file_path):
29            print('ファイルが見つかりませんでした。')
30            return False
31        _, ext = os.path.splitext(self.mp3_file_path)
32        if ext != '.mp3':
33            print('拡張子が{}です。mp3ファイルを指定してください。'.format(ext))
34            return False
35        return True
36
37    def count_down(self):
38        if not self.validate_arg_minutes():
39            return
40        if not self.validate_arg_mp3_filepath():
41            return
42
43        while self.minutes >= 0 and self.seconds >= 0:
44            print('\r残り時間: {}:{:0>2}'.format(self.minutes, self.seconds), end='')
45            self.seconds -= 1
46            if self.seconds < 0:
47                self.minutes -= 1
48                self.seconds = 59
49            if self.minutes < 0:
50                break
51            time.sleep(1)
52
53        pygame.mixer.init()
54        pygame.mixer.music.load(self.mp3_file_path)
55        mp3_length = MP3(self.mp3_file_path).info.length
56
57        print('\n時間になりました')
58        print('終了するにはCtrl+Cを押して下さい')
59
60        try:
61            while True:
62                pygame.mixer.music.play(1)
63                time.sleep(mp3_length + 0.1)
64        except KeyboardInterrupt:
65            pygame.mixer_music.stop()
66            sys.exit()
67
68
69if __name__ == '__main__':
70    parser = argparse.ArgumentParser(description='引数で指定した時間(分単位)後にmp3ファイルを鳴らす')
71    parser.add_argument('minutes', type=int, help='指定時間(分単位)')
72    parser.add_argument('mp3_file_path', type=str, help='mp3ファイルのパス')
73
74    args = parser.parse_args()
75    countdown_timer = CountDownTimer(args.minutes, args.mp3_file_path)
76    countdown_timer.count_down()

コンソールアプリケーションの引数の解析にはsys.argvも使用できますがargparseがおすすめです。

mp3ファイルを再生する部分はpygamemutagenを使用してます。

githubにテストコードも含めて置いてあります。
https://github.com/kazusapg/countdown_timer

関連ページ