python每天定时发送脚本

最近业务上需要每天解析txt文本或者excel文件,读取内容发送短信,发送的时间段可控,用python实现

安装pip依赖

pip install -r requirement.txt

xlrd
PyYAML

yaml配置

#读取文件路径
file_path: /Users/user/

send_mode:
  # 早于开始时间则于日常开始时间发送,始末时间之间则立即发送,晚于结束时间不发送
  begin_time: "08:30:00"
  end_time: "17:30:00"

代码

# coding: utf-8
from socket import *
from threading import Timer
import sys
import string
import datetime
import time
import os
import xlrd
import yaml
import chardet

def read_txt(send_path):
    file = open(send_path, 'r')
    phones = file.read().splitlines()

    list = []
    for i in range(0, len(phones)):
        # 去掉头尾的双引号
        if phones[i].find("\"") >= 0:
            phones[i] = phones[i][1:-1]
        array = phones[i].split()
        obj = {
            "phno": array[0],
            "text": array[1]
        }
        print obj
        list.append(obj)
    file.close()

    return list


def read_excel(send_path):
    sheet1 = xlrd.open_workbook(send_path).sheet_by_index(0)

    list = []
    for i in range(0, sheet1.nrows):
        obj = {
            "phno": str(int(sheet1.cell_value(i, 0))),
            "text": sheet1.cell_value(i, 1)
        }

        list.append(obj)

    return list


# 从文本中获取发送信息,txt,excel
def get_data():
    file_list = os.popen('ls ' + FILE_PATH).read().split()

    if len(file_list) > 0:
        today = datetime.date.today()
        send_time = today - datetime.timedelta(days=1)

        send_path = ""
        for i in range(0, len(file_list)):
            if file_list[i].find(str(send_time)) >= 0:
                filename = file_list[i]
                send_path = os.path.join(FILE_PATH, filename)
                print send_path
                break

        if send_path != "":
            if os.path.exists(send_path):
                # 获取文件名后缀
                type = os.path.splitext(send_path)[-1][1:].lower()
                if type == 'txt':
                    list = read_txt(send_path)
                elif type == 'xlsx':
                    list = read_excel(send_path)

                return list
        else:
            print "file not exist"


    else:
        print 'location not exist'

    return []


# 宁波短信接口
def send_nb(list):
    # 业务参数
    datatype = '0000'
    inst = '000000'
    cate = '00'
    sendtime = "0" * 20
    expa = "0"

    for i in range(0, len(list)):
        # 手机号码
        phno = list[i]['phno']
        # 短信内容
        text = list[i]['text']

        strphno = phno.ljust(20)
        message = datatype + inst + cate + sendtime + expa + strphno + text
        message = str(len(message) + 4).zfill(4) + message

        # 短信接口请求ip
        s = socket(AF_INET, SOCK_STREAM)
        s.connect((ip,port))
        s.send(message.decode('utf-8').encode("gbk"))
        while  True:
            data = s.recv(1024)
            if not data:
                break
            else:
                print data
                break
        s.close()

    print 'send finished'


if __name__ == "__main__":
    reload(sys)
    sys.setdefaultencoding('utf-8')

    current_path = os.path.abspath(os.path.dirname(__file__))
    yaml_path = os.path.join(current_path, "config.yaml")
    with open(yaml_path, 'r') as f:
        config = yaml.load(f)
    FILE_PATH = config['file_path']
    begin_time = config['send_mode']['begin_time']
    end_time = config['send_mode']['end_time']

    list = get_data()

    if len(list) > 0:
        # 发送时间判断,早于开始时间则于日常开始时间发送,始末时间之间则立即发送,晚于结束时间不发送
        now_time = time.strftime("%H:%M:%S", time.localtime())
        print begin_time + ' ' + end_time
        print now_time

        if now_time < begin_time:
            begin_today = datetime.datetime.strptime(time.strftime("%Y-%m-%d", time.localtime()) + " " + begin_time,
                                                     "%Y-%m-%d %H:%M:%S")
            now_unix = datetime.datetime.now()
            # 间隔执行时间
            diff_time = (begin_today - now_unix).seconds
            print "send daily: " + str(diff_time) + " seconds"

            t = Timer(diff_time, send_nb, (list,))
            t.start()

        elif now_time <= end_time:
            print "send now"
            send_nb(list)
        else:
            print "not send"

猜你喜欢

转载自www.cnblogs.com/wanli002/p/10504983.html
今日推荐