python, 实现朋友家人年历生日自动提醒

为了方便提醒本身,今天有哪位朋友过生日(年历生日)。python

测试环境:fedora25桌面版。bash

 

创建一个生日配置文件,注意:按日期排好序测试

vi /etc/birthday.txtthis

朋友A 1-4
朋友C 2-3
朋友B 3-8

 

建立脚本文件spa

建立脚本文件 /usr/bin/check_birthday, 脚本内容以下。code

#!/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]))

 

设置脚本执行权限crontab

chmod 777 /usr/bin/check_birthdayip

 

下载LunarDate模块utf-8

pip install LunarDateget

提示:若是系统中没有安装pip,先安装pip(yum install -y pip)

 

检查今天是否有人过生日

check_birthday

 

能够设置天天定时检查

经过crontab -e进行设置

# 天天12,20点检查一次

0 12,20 * * * /usr/bin/check_birthday
相关文章
相关标签/搜索