Python3 循环定时休息并播放音乐 (Windows)

功能:工作一段时间(40 min),自动定时休息(10 min)并播放音乐,如此循环

文件名EyeTimer.pyw,直接双击运行

关闭方法:在任务管理器里结束 Python 进程

 1#coding=utf-8
 2
 3from ctypes import *
 4from ctypes.wintypes import *
 5import time, easygui as g
 6import os
 7import pygame
 8import random
 9import linecache
10 
11HWND_BROADCAST = 0xffff
12WM_SYSCOMMAND = 0x0112
13SC_MONITORPOWER = 0xF170
14MonitorPowerOff = 2
15SW_SHOW = 5
16 
17def main():
18  boolLongTime = False
19  user32 = windll.LoadLibrary('user32.dll')
20  shell32 = windll.LoadLibrary("shell32.dll")
21  stopMusic = 'stop.wav'
22  count = len(open('mp3_list.txt', 'rU',encoding='utf-8').readlines())
23
24  while 1:  
25    if boolLongTime == False:
26      time.sleep(40 * 60)  #工作 40 min
27
28      g.msgbox("可以休息一下了", title="提醒",ok_button="确定")        
29      
30      pygame.mixer.init()
31      pygame.mixer.music.load(stopMusic)
32      pygame.mixer.music.play()
33      pygame.time.delay(10000)	
34			
35      #取随机数,以便随机播放mp3_list.txt中的任一首
36      randomfile = random.randint(0, count)
37
38      path1 = linecache.getline('mp3_list.txt', randomfile)	
39      path1 = path1.replace('\\', '//')
40      path1 = path1.replace('\n', '')
41			
42      pygame.mixer.music.load(path1.encode())
43      pygame.mixer.music.play()
44
45      #调用 API 实现 锁屏,熄屏
46      #PostMessageW(hWnd,WM_RECVDATA,0,(LPARAM)tempBuf)
47      windll.user32.PostMessageW(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, MonitorPowerOff)   
48      shell32.ShellExecuteW(None,'open', 'rundll32.exe', 'USER32,LockWorkStation','',SW_SHOW)
49      
50      boolLongTime = True
51    else:
52      time.sleep(10 * 60)  #休息10 min
53      pygame.mixer.init() 
54      pygame.mixer.music.load(stopMusic)
55      pygame.mixer.music.play()
56      pygame.time.delay(10000)
57      
58      pygame.mixer.music.stop()
59      boolLongTime = False
60 
61if __name__ == "__main__":
62    main()