闹铃小助手

为了建立学习的仪式感,我自己写了一套程序,尽可能让自己避免外界因素的干扰,以达到专注的目的。现在我把代码写到博客上,与大家一起分享一下。

注意:windows下使用playsound需要修改一下源码,源码有点小问题,文末有改后的源码。

1.导入所需模块

import sys
import time
import playsound as pl
from multiprocessing import Process

2.主函数,设置时间的安排,函数执行从上到下依次执行,这个需要自己定好这段时间自己打算做什么。

def main():work(minutes=20, todo='blog')work(minutes=30, todo='recite words')rest(minutes=10)work(minutes=60, todo='programming')

例如上述代码,写blog20分钟,背单词30分钟,休息10分钟,编程60分钟,以此类推。只要指定参数即可。

3.开始工作:使用时间进程和工作进程。

def work(minutes, todo):working = Process(target=startWorking, name=todo, args=(todo,))timing = Process(target=timePassing, args=(minutes,), name='timePassing')working.start()timing.start()timing.join()working.join()working.close()timing.close()

4.开始休息:使用时间进程和休息进程。

def rest(minutes):timing = Process(target=timePassing, args=(minutes,), name='timePassing')resting = Process(target=startRest, name='startWorking')resting.start()timing.start()timing.join()resting.join()resting.close()timing.close()

5.时间、工作、休息三个进程对应的函数:

def startWorking(todo):print('开始干活啦!!')print('todo:', todo)pl.playsound('piano.mp3')  # 音乐响起def startRest():print('开始休息啦!!')pl.playsound('exercise.mp3')  # 音乐响起def timePassing(minutes):print('=' * 20, '开始计时', '=' * 20)seconds = minutes * 60for i in range(round(seconds))[::-1]:time.sleep(1)sys.stdout.write(f'\r倒计时:{i // 60}分{i % 60}秒')sys.stdout.flush()print('\n' + '=' * 20, '计时结束', '=' * 20)

播放的音乐可以自己指定哦。

这个是修改之后的playsound源码,可以直接拷贝导入使用。

import logging
logger = logging.getLogger(__name__)class PlaysoundException(Exception):passdef _canonicalizePath(path):"""Support passing in a pathlib.Path-like object by converting to str."""import sysif sys.version_info[0] >= 3:return str(path)else:# On earlier Python versions, str is a byte string, so attempting to# convert a unicode string to str will fail. Leave it alone in this case.return pathdef _playsoundWin(sound, block = True):'''Utilizes windll.winmm. Tested and known to work with MP3 and WAVE onWindows 7 with Python 2.7. Probably works with more file formats.Probably works on Windows XP thru Windows 10. Probably works with allversions of Python.Inspired by (but not copied from) Michael Gundlach <gundlach@gmail.com>'s mp3play:https://github.com/michaelgundlach/mp3playI never would have tried using windll.winmm without seeing his code.'''sound = _canonicalizePath(sound)if any((c in sound for c in ' "\'()')):from os       import close, removefrom os.path  import splitextfrom shutil   import copyfrom tempfile import mkstempfd, tempPath = mkstemp(prefix = 'PS', suffix = splitext(sound)[1])  # Avoid generating files longer than 8.3 characters.logger.info('Made a temporary copy of {} at {} - use other filenames with only safe characters to avoid this.'.format(sound, tempPath))copy(sound, tempPath)close(fd)  # mkstemp opens the file, but it must be closed before MCI can open it.try:_playsoundWin(tempPath, block)finally:remove(tempPath)returnfrom ctypes import c_buffer, windllfrom time   import sleepdef winCommand(*command):bufLen = 600buf = c_buffer(bufLen)command = ' '.join(command)errorCode = int(windll.winmm.mciSendStringW(command, buf, bufLen - 1, 0))  # use widestring version of the functionif errorCode:errorBuffer = c_buffer(bufLen)windll.winmm.mciGetErrorStringW(errorCode, errorBuffer, bufLen - 1)  # use widestring version of the functionexceptionMessage = ('\n    Error ' + str(errorCode) + ' for command:''\n        ' + command +'\n    ' + errorBuffer.raw.decode('utf-16').rstrip('\0'))logger.error(exceptionMessage)raise PlaysoundException(exceptionMessage)return buf.valueif '\\' in sound:sound = '"' + sound + '"'try:logger.debug('Starting')winCommand(u'open {}'.format(sound))winCommand(u'play {}{}'.format(sound, ' wait' if block else ''))logger.debug('Returning')finally:try:winCommand(u'close {}'.format(sound))except PlaysoundException:logger.warning(u'Failed to close the file: {}'.format(sound))# If it fails, there's nothing more that can be done...passdef _handlePathOSX(sound):sound = _canonicalizePath(sound)if '://' not in sound:if not sound.startswith('/'):from os import getcwdsound = getcwd() + '/' + soundsound = 'file://' + soundtry:# Don't double-encode it.sound.encode('ascii')return sound.replace(' ', '%20')except UnicodeEncodeError:try:from urllib.parse import quote  # Try the Python 3 import first...except ImportError:from urllib import quote  # Try using the Python 2 import before giving up entirely...parts = sound.split('://', 1)return parts[0] + '://' + quote(parts[1].encode('utf-8')).replace(' ', '%20')def _playsoundOSX(sound, block = True):'''Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE onOS X 10.11 with Python 2.7. Probably works with anything QuickTime supports.Probably works on OS X 10.5 and newer. Probably works with all versions ofPython.Inspired by (but not copied from) Aaron's Stack Overflow answer here:http://stackoverflow.com/a/34568298/901641I never would have tried using AppKit.NSSound without seeing his code.'''try:from AppKit import NSSoundexcept ImportError:logger.warning("playsound could not find a copy of AppKit - falling back to using macOS's system copy.")sys.path.append('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC')from AppKit import NSSoundfrom Foundation import NSURLfrom time       import sleepsound = _handlePathOSX(sound)url   = NSURL.URLWithString_(sound)if not url:raise PlaysoundException('Cannot find a sound with filename: ' + sound)for i in range(5):nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True)if nssound:breakelse:logger.debug('Failed to load sound, although url was good... ' + sound)else:raise PlaysoundException('Could not load sound with filename, although URL was good... ' + sound)nssound.play()if block:sleep(nssound.duration())def _playsoundNix(sound, block = True):"""Play a sound using GStreamer.Inspired by this:https://gstreamer.freedesktop.org/documentation/tutorials/playback/playbin-usage.html"""sound = _canonicalizePath(sound)# pathname2url escapes non-URL-safe charactersfrom os.path import abspath, existstry:from urllib.request import pathname2urlexcept ImportError:# python 2from urllib import pathname2urlimport gigi.require_version('Gst', '1.0')from gi.repository import GstGst.init(None)playbin = Gst.ElementFactory.make('playbin', 'playbin')if sound.startswith(('http://', 'https://')):playbin.props.uri = soundelse:path = abspath(sound)if not exists(path):raise PlaysoundException(u'File not found: {}'.format(path))playbin.props.uri = 'file://' + pathname2url(path)set_result = playbin.set_state(Gst.State.PLAYING)if set_result != Gst.StateChangeReturn.ASYNC:raise PlaysoundException("playbin.set_state returned " + repr(set_result))# FIXME: use some other bus method than poll() with block=False# https://lazka.github.io/pgi-docs/#Gst-1.0/classes/Bus.htmllogger.debug('Starting play')if block:bus = playbin.get_bus()try:bus.poll(Gst.MessageType.EOS, Gst.CLOCK_TIME_NONE)finally:playbin.set_state(Gst.State.NULL)logger.debug('Finishing play')def _playsoundAnotherPython(otherPython, sound, block = True, macOS = False):'''Mostly written so that when this is run on python3 on macOS, it can invokepython2 on macOS... but maybe this idea could be useful on linux, too.'''from inspect    import getsourcefilefrom os.path    import abspath, existsfrom subprocess import check_callfrom threading  import Threadsound = _canonicalizePath(sound)class PropogatingThread(Thread):def run(self):self.exc = Nonetry:self.ret = self._target(*self._args, **self._kwargs)except BaseException as e:self.exc = edef join(self, timeout = None):super().join(timeout)if self.exc:raise self.excreturn self.ret# Check if the file exists...if not exists(abspath(sound)):raise PlaysoundException('Cannot find a sound with filename: ' + sound)playsoundPath = abspath(getsourcefile(lambda: 0))t = PropogatingThread(target = lambda: check_call([otherPython, playsoundPath, _handlePathOSX(sound) if macOS else sound]))t.start()if block:t.join()from platform import system
system = system()if system == 'Windows':playsound = _playsoundWin
elif system == 'Darwin':playsound = _playsoundOSXimport sysif sys.version_info[0] > 2:try:from AppKit import NSSoundexcept ImportError:logger.warning("playsound is relying on a python 2 subprocess. Please use `pip3 install PyObjC` if you want playsound to run more efficiently.")playsound = lambda sound, block = True: _playsoundAnotherPython('/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python', sound, block, macOS = True)
else:playsound = _playsoundNixif __name__ != '__main__':  # Ensure we don't infinitely recurse trying to get another python instance.try:import gigi.require_version('Gst', '1.0')from gi.repository import Gstexcept:logger.warning("playsound is relying on another python subprocess. Please use `pip install pygobject` if you want playsound to run more efficiently.")playsound = lambda sound, block = True: _playsoundAnotherPython('/usr/bin/python3', sound, block, macOS = False)del systemif __name__ == '__main__':# block is always True if you choose to run this from the command line.from sys import argvplaysound(argv[1])

居家学习python自制闹铃小助手相关推荐

  1. Python实现王者荣耀小助手(一)

    简单来说网络爬虫,是指抓取万维网信息的程序或者脚本,Python在网络爬虫有很大优势,今天我们用Python实现获取王者荣耀相关数据,做一个小助手: 前期准备,环境搭建: Python2.7 sys模 ...

  2. python登录界面源码_基于Python的自媒体小助手---登录页面的实现代码

    核心技术:Python3.7 GUI技术:Tkinter (Python已经内置) 好多文章写Python GUI之tkinter窗口视窗教程大集合(看这篇就够了) 我看了N遍也没够好多东西都没有就基 ...

  3. Python实现王者荣耀小助手(二)

    接下来我们获取英雄和武器信息,详细代码KingGlory.py如下(代码中有详细注解): # -*- coding: utf-8 -*- #!/usr/bin/env python # @Time : ...

  4. python游戏脚本dnf_一款Python自制的斗地主小游戏

    [实例简介] 一款Python自制的斗地主小游戏 [实例截图] [核心代码] 斗地主_Raffeale └── dist ├── avbin.dll ├── DouDiZhu.exe ├── gui_ ...

  5. 利用Python自制雷霆战机小游戏,娱乐编程,快乐学习!

    开发工具 Python版本:3.6.4 相关模块: pygame模块: 以及一些Python自带的模块. 环境搭建 安装Python并添加到环境变量,pip安装需要的相关模块即可. 先睹为快 在cmd ...

  6. python写出雷霆战机_利用Python自制雷霆战机小游戏,娱乐编程,快乐学习!

    开发工具 Python版本:3.6.4 相关模块: pygame模块: 以及一些Python自带的模块. 环境搭建 安装Python并添加到环境变量,pip安装需要的相关模块即可. 先睹为快 在cmd ...

  7. Python 实现 一键Wifi小助手

    这个小程序已经放到 github 上面,欢迎交流:https://github.com/AngryHacker/Wifi_Assistant ============================= ...

  8. python学什么教学_学习python的几个小技巧

    提示1:每天编码 学习新语言时,一致性非常重要.我们建议每天做出代码承诺.可能难以置信,但是肌肉记忆在编程中起着很大的作用.每天致力于编码将真正帮助发展肌肉记忆.尽管乍一看似乎令人生畏,但考虑每天从2 ...

  9. 自制360开机小助手

    每次开机看到360的开机小助手,都非常羡慕,要是自己写一个多好啊. 今天,pearry就带大家来自己动手写开机小助手. 主要知识: 1.获取系统运行时间 涉及的API函数:GetTickCount() ...

最新文章

  1. python学习笔记(三)—— 序列类型及方法(列表、元组、字符串)
  2. 浅谈WebKit之JavaScriptCore/V8
  3. 银行利率是5.45%,房贷是4.9%,有钱该提前还房贷还是存款?
  4. G - Tiling FZU - 2040(未解决)
  5. win7下卸载linux系统(不用windows光盘)
  6. C++派生类的构造函数和析构函数
  7. 7-18 QQ帐户的申请与登陆 (10 分)
  8. 卷积面试题(最重要)
  9. 命名实体识别(NER)资料收集
  10. 【云游戏】云游戏的架构设计和技术实现
  11. mac端锐捷无法验证服务器,还在为mac无法用锐捷认证校园网登陆而郁闷吗?
  12. SRE从踩坑到牛逼(二)利用Python进行Arcgis站点分析+Nginx日志分析
  13. 计算机组装配置(Win10蓝屏错误代码大全详解)
  14. ssh登录windows
  15. 【莫烦Python】Python 基础教程——学习笔记
  16. 史上最全!56个JavaScript的「手写」知识点,扫盲啦!
  17. 蚂蚁金服“定损宝”现身AI顶级会议NeurIPS 1
  18. linux 之 echo命令用法
  19. window10或XP 定时换壁纸,添加计划到windows任务里,cmd换壁纸
  20. 《Python编程从入门到实践》袁国忠 译 P1~P200学习笔记

热门文章

  1. 后摩尔时代新星之自旋电子器件
  2. Linux笔记本 安装 qq/TIM/微信/百度网盘......解决方案
  3. ITK入门教程(12)点集之得到存储的点
  4. 刚装修的房子多久能住?集成墙面真的好吗?
  5. Mac 在启动时显示的各种界面图标说明:禁止符号、问号、空白屏幕、锁定等
  6. angular+bootstrap+spring boot实现分页
  7. preLaunchTask“C/C++:g++.exe生成活动文件“已终止,退出代码为-1
  8. 放弃了又何需执着 ?
  9. android graphics2d,Graphics2D的drawString之不带颜色的字体
  10. 股票交易sdk接口是什么意思?