python實現的解析crontab設定檔代碼

來源:互聯網
上載者:User
#/usr/bin/env python#-*- coding:utf-8 -*- """1.解析 crontab 設定檔中的五個數間參數(分 時 日 月 周),擷取他們對應的取值範圍2.將時間戳記與crontab配置中一行時間參數對比,判斷該時間戳記是否在配置設定的時間範圍內""" #$Id $ import re, time, sysfrom Core.FDateTime.FDateTime import FDateTime def get_struct_time(time_stamp_int):"""按整型時間戳記擷取格式化時間 分 時 日 月 周Args:time_stamp_int 為傳入的值為時間戳記(整形),如:1332888820經過localtime轉換後變成time.struct_time(tm_year=2012, tm_mon=3, tm_mday=28, tm_hour=6, tm_min=53, tm_sec=40, tm_wday=2, tm_yday=88, tm_isdst=0)Return:list____返回 分 時 日 月 周""" st_time = time.localtime(time_stamp_int)return [st_time.tm_min, st_time.tm_hour, st_time.tm_mday, st_time.tm_mon, st_time.tm_wday]  def get_strptime(time_str, str_format):"""從字串擷取 整型時間戳記Args:time_str 字串類型的時間戳記 如 '31/Jul/2013:17:46:01'str_format 指定 time_str 的格式 如 '%d/%b/%Y:%H:%M:%S'Return:返回10位整型(int)時間戳記,如 1375146861"""return int(time.mktime(time.strptime(time_str, str_format))) def get_str_time(time_stamp, str_format='%Y%m%d%H%M'):"""擷取時間戳記,Args:time_stamp 10位整型(int)時間戳記,如 1375146861str_format 指定返回格式,實值型別為 字串 strRturn:返回格式 預設為 年月日時分,如2013年7月9日1時3分 :201207090103"""return time.strftime("%s" % str_format, time.localtime(time_stamp)) def match_cont(patten, cont):"""正則匹配(精確符合的匹配)Args:patten Regexcont____ 匹配內容Return:True or False"""res = re.match(patten, cont)if res:return Trueelse:return False def handle_num(val, ranges=(0, 100), res=list()):"""處理純數字"""val = int(val)if val >= ranges[0] and val <= ranges[1]:res.append(val)return res def handle_nlist(val, ranges=(0, 100), res=list()):"""處理數字列表 如 1,2,3,6"""val_list = val.split(',')for tmp_val in val_list:tmp_val = int(tmp_val)if tmp_val >= ranges[0] and tmp_val <= ranges[1]:res.append(tmp_val)return res def handle_star(val, ranges=(0, 100), res=list()):"""處理星號"""if val == '*':tmp_val = ranges[0]while tmp_val <= ranges[1]:res.append(tmp_val)tmp_val = tmp_val + 1return res def handle_starnum(val, ranges=(0, 100), res=list()):"""星號/數字 組合 如 */3"""tmp = val.split('/')val_step = int(tmp[1])if val_step < 1:return resval_tmp = int(tmp[1])while val_tmp <= ranges[1]:res.append(val_tmp)val_tmp = val_tmp + val_stepreturn res def handle_range(val, ranges=(0, 100), res=list()):"""處理區間 如 8-20"""tmp = val.split('-')range1 = int(tmp[0])range2 = int(tmp[1])tmp_val = range1if range1 < 0:return reswhile tmp_val <= range2 and tmp_val <= ranges[1]:res.append(tmp_val)tmp_val = tmp_val + 1return res def handle_rangedv(val, ranges=(0, 100), res=list()):"""處理區間/步長 組合 如 8-20/3 """tmp = val.split('/')range2 = tmp[0].split('-')val_start = int(range2[0])val_end = int(range2[1])val_step = int(tmp[1])if (val_step < 1) or (val_start < 0):return resval_tmp = val_startwhile val_tmp <= val_end and val_tmp <= ranges[1]:res.append(val_tmp)val_tmp = val_tmp + val_stepreturn res def parse_conf(conf, ranges=(0, 100), res=list()):"""解析crontab 五個時間參數中的任意一個"""#去除空格,再拆分conf = conf.strip(' ').strip(' ')conf_list = conf.split(',')other_conf = []number_conf = []for conf_val in conf_list:if match_cont(PATTEN['number'], conf_val):#記錄拆分後的純數字參數number_conf.append(conf_val)else:#記錄拆分後純數字以外的參數,如萬用字元 * , 區間 0-8, 及 0-8/3 之類other_conf.append(conf_val)if other_conf:#處理純數字外各種參數for conf_val in other_conf:for key, ptn in PATTEN.items():if match_cont(ptn, conf_val):res = PATTEN_HANDLER[key](val=conf_val, ranges=ranges, res=res)if number_conf:if len(number_conf) > 1 or other_conf:#純數字多於1,或純數字與其它參數共存,則數字作為時間列表res = handle_nlist(val=','.join(number_conf), ranges=ranges, res=res)else:#只有一個純數字存在,則數字為時間 間隔res = handle_num(val=number_conf[0], ranges=ranges, res=res)return res def parse_crontab_time(conf_string):"""解析crontab時間配置參數Args:conf_string  配置內容(共五個值:分 時 日 月 周) 取值範圍 分鐘:0-59 小時:1-23 日期:1-31 月份:1-12 星期:0-6(0表示周日)Return:crontab_range list格式,分 時 日 月 周 五個傳入參數分別對應的取值範圍"""time_limit= ((0, 59), (1, 23), (1, 31), (1, 12), (0, 6))crontab_range = []clist = []conf_length = 5tmp_list = conf_string.split(' ')for val in tmp_list:if len(clist) == conf_length:breakif val:clist.append(val) if len(clist) != conf_length:return -1, 'config error whith [%s]' % conf_stringcindex = 0for conf in clist:res_conf = []res_conf = parse_conf(conf, ranges=time_limit[cindex], res=res_conf)if not res_conf:return -1, 'config error whith [%s]' % conf_stringcrontab_range.append(res_conf)cindex = cindex + 1return 0, crontab_range def time_match_crontab(crontab_time, time_struct):"""將時間戳記與crontab配置中一行時間參數對比,判斷該時間戳記是否在配置設定的時間範圍內Args:crontab_time____crontab配置中的五個時間(分 時 日 月 周)參數對應時間取值範圍time_struct____ 某個整型時間戳記,如:1375027200 對應的 分 時 日 月 周Return:tuple 狀態代碼, 狀態原因"""cindex = 0for val in time_struct:if val not in crontab_time[cindex]:return 0, Falsecindex = cindex + 1return 0, True def close_to_cron(crontab_time, time_struct):"""coron的指定範圍(crontab_time)中 最接近 指定時間 time_struct 的值"""close_time = time_structcindex = 0for val_struct in time_struct:offset_min = val_structval_close = val_structfor val_cron in crontab_time[cindex]:offset_tmp = val_struct - val_cronif offset_tmp > 0 and offset_tmp < offset_min:val_close = val_structoffset_min = offset_tmpclose_time[cindex] = val_closecindex = cindex + 1return close_time def cron_time_list(cron_time,year_num=int(get_str_time(time.time(), "%Y")),limit_start=get_str_time(time.time(), "%Y%m%d%H%M"),limit_end=get_str_time(time.time() + 86400, "%Y%m%d%H%M")):#print "\nfrom ", limit_start , ' to ' ,limit_end"""擷取crontab時間配置參數取值範圍內的所有時間點 的 時間戳記Args:cron_time 符合crontab配置指定的所有時間點year_num____指定在哪一年內 擷取limit_start 開始時間Rturn:List  所有時間點組成的列表(年月日時分 組成的時間,如2013年7月29日18時56分:201307291856)"""#按小時 和 分鐘組裝hour_minute = []for minute in cron_time[0]:minute = str(minute)if len(minute) < 2:minute = '0%s' % minutefor hour in cron_time[1]:hour = str(hour)if len(hour) < 2:hour = '0%s' % hourhour_minute.append('%s%s' % (hour, minute))#按天 和 小時組裝day_hm = []for day in cron_time[2]:day = str(day)if len(day) < 2:day = '0%s' % dayfor hour_mnt in hour_minute:day_hm.append('%s%s' % (day, hour_mnt))#按月 和 天組裝month_dhm = []#只有30天的月份month_short = ['02', '04', '06', '09', '11']for month in cron_time[3]:month = str(month)if len(month) < 2:month = '0%s' % monthfor day_hm_s in day_hm:if month == '02':if (((not year_num % 4 ) and (year_num % 100)) or (not year_num % 400)):#閏年2月份有29天if int(day_hm_s[:2]) > 29:continueelse:#其它2月份有28天if int(day_hm_s[:2]) > 28:continueif month in month_short:if int(day_hm_s[:2]) > 30:continuemonth_dhm.append('%s%s' % (month, day_hm_s))#按年 和 月組裝len_start = len(limit_start)len_end = len(limit_end)month_dhm_limit = []for month_dhm_s in month_dhm:time_ymdhm = '%s%s' % (str(year_num), month_dhm_s)#開始時間\結束時間以外的排除if (int(time_ymdhm[:len_start]) < int(limit_start)) or \ (int(time_ymdhm[:len_end]) > int(limit_end)):continuemonth_dhm_limit.append(time_ymdhm)if len(cron_time[4]) < 7:#按不在每周指定時間的排除month_dhm_week = []for time_minute in month_dhm_limit:str_time = time.strptime(time_minute, '%Y%m%d%H%M%S')if str_time.tm_wday in cron_time[4]:month_dhm_week.append(time_minute)return month_dhm_weekreturn month_dhm_limit  #crontab時間參數各種寫法 的 正則匹配PATTEN = {#純數字'number':'^[0-9]+$',#數字列表,如 1,2,3,6'num_list':'^[0-9]+([,][0-9]+)+$',#星號 *'star':'^\*$',#星號/數字 組合,如 */3'star_num':'^\*\/[0-9]+$',#區間 如 8-20'range':'^[0-9]+[\-][0-9]+$',#區間/步長 組合 如 8-20/3'range_div':'^[0-9]+[\-][0-9]+[\/][0-9]+$'#區間/步長 列表 組合,如 8-20/3,21,22,34#'range_div_list':'^([0-9]+[\-][0-9]+[\/][0-9]+)([,][0-9]+)+$'}#各正則對應的處理方法PATTEN_HANDLER = {'number':handle_num,'num_list':handle_nlist,'star':handle_star,'star_num':handle_starnum,'range':handle_range,'range_div':handle_rangedv}  def isdo(strs,tips=None):"""判斷是否匹配成功!"""try:tips = tips==None and "檔案名稱格式錯誤:job_月-周-天-時-分_檔案名稱.txt" or tipstimer = strs.replace('@',"*").replace('%','/').split('_')[1]month,week,day,hour,mins = timer.split('-')conf_string = mins+" "+hour+" "+day+" "+month+" "+weekres, desc = parse_crontab_time(conf_string)if res == 0:cron_time = descelse:return False now =FDateTime.now()now = FDateTime.datetostring(now, "%Y%m%d%H%M00") time_stamp = FDateTime.strtotime(now, "%Y%m%d%H%M00") #time_stamp = int(time.time())#解析 時間戳記對應的 分 時 日 月 周time_struct = get_struct_time(time_stamp)match_res = time_match_crontab(cron_time, time_struct)return match_res[1]except:print tipsreturn False def main():"""測試用執行個體"""#crontab配置中一行時間參數#conf_string = '*/10 * * * * (cd /opt/pythonpm/devpapps; /usr/local/bin/python2.5 data_test.py>>output_error.txt)'conf_string = '*/10 * * * *'#時間戳記time_stamp = int(time.time()) #解析crontab時間配置參數 分 時 日 月 周 各個取值範圍res, desc = parse_crontab_time(conf_string) if res == 0:cron_time = descelse:print descsys, exit(-1) print "\nconfig:", conf_stringprint "\nparse result(range for crontab):" print " minute:", cron_time[0]print " hour: ", cron_time[1]print " day: ", cron_time[2]print " month: ", cron_time[3]print " week day:", cron_time[4] #解析 時間戳記對應的 分 時 日 月 周time_struct = get_struct_time(time_stamp)print "\nstruct time(minute hour day month week) for %d :" % \ time_stamp, time_struct #將時間戳記與crontab配置中一行時間參數對比,判斷該時間戳記是否在配置設定的時間範圍內match_res = time_match_crontab(cron_time, time_struct)print "\nmatching result:", match_res #crontab配置定義範圍中最近接近時指定間戳的一組時間most_close = close_to_cron(cron_time, time_struct)print "\nin range of crontab time which is most colse to struct ", most_close time_list = cron_time_list(cron_time)print "\n\n %d times need to tart-up:\n" % len(time_list)print time_list[:10], '...'  if __name__ == '__main__':#請看 使用執行個體strs = 'job_@-@-@-@-@_test02.txt.sh'print isdo(strs) #main()0")
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.