Python干货|生日记忆器:再也不担心跟女朋友吵架了

160 阅读1分钟

这个应用程序有助于提醒你的生日和通知你朋友的生日。

这个应用程序使用Python和Ubuntu通知在每次启动系统时通知用户。

创建脚本文件 /usr/bin/check_birthday, 脚本内容如下。

#!/usr/bin/python
# -*- coding: utf-8 -*-

from lunardate import LunarDate
import os
import sys

def get_month_day(datestring):
    array = datestring.split("-")

    if len(array) == 3:
        (y, m, d) = array
        return int(m), int(d)
    else:
        (m, d) = array
        return int(m), int(d)


def is_birthday_today(date, birthday):
    m, d = get_month_day(birthday)
    return m == date.month and d == date.day


def distance_birthday_today(date, birthday):
    m, d = get_month_day(birthday)
    return (m - date.month) * 30 + d - date.day


def showtip(line):
    os.system('zenity --info --title "title" --text "' + line + '" --width=300 --height=200')


filename='/etc/birthday.txt'
lines = open(filename).readlines()

lines = map(lambda x: x.strip(), lines)
lines = filter(lambda x: x != "", lines)


if len(lines) == 0 or lines[0].strip() == "":
  print("配置文件%s中没有数据" % filename)
  sys.exit(1)

today = LunarDate.today()

exist_someone_birthday = False

# 查找谁今天过生日
for line in lines:
    array = line.split()
    if is_birthday_today(today, array[1]):
        exist_someone_birthday = True
        showtip("今天生日, " + line)
        sys.exit(0)

all_finish_this_year = True
# 提醒谁快要过生日
if not exist_someone_birthday:
    for line in lines:
        array = line.split()
        if distance_birthday_today(today, array[1]) > 0:
	    all_finish_this_year = False
            showtip("今天%d-%d, %s" % (today.month, today.day, line))
            sys.exit(0)

if all_finish_this_year:
  showtip("今天%d-%d, %s" % (today.month, today.day, lines[0]))

设置脚本执行权限

chmod 777 /usr/bin/check_birthday

下载LunarDate模块

pip install LunarDate

提示:如果系统中没有安装pip,请先安装pip(yum install -y pip)

检查今天是否有人过生日

check_birthday

可以设置每天定时检查

通过crontab -e进行设置

# 每天12,20点检查一次

0 12,20 * * * /usr/bin/check_birthday

还可以通过这样的方法:爬取日历后,建立具体朋友生日表进行匹配,发邮件提醒