Parse crontab configuration file code implemented by Python

Source: Internet
Author: User
Tags ranges
#/usr/bin/env python#-*-coding:utf-8-*-"" "1. Parse the five-digit parameter in the crontab configuration file (time-sharing week) get their corresponding range of values 2. Compare the timestamp with a row of time parameters in the crontab configuration to determine if the timestamp is within the configured time range "" "# $Id $ import Re, times, Sysfrom Core.FDateTime.FDateTime Import Fdatetime def get_struct_time (time_stamp_int): "" "gets the formatted time of day by integer timestamp args:time_stamp_int for the passed value is timestamp (shaping), such as: 1332888820 after localtime converted into 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____ return time-of-Day Week "" "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): "" " Gets the integer timestamp from the string args:time_str the timestamp of the string type as ' 31/jul/2013:17:46:01 ' str_format specifies the format of the time_str as '%d/%b/%y:%h:%m:%s ' Return: Returns a 10-bit integer (int) timestamp, such as 1375146861 "" "Return Int (Time.mktime (Time.strptime (Time_str, Str_format))) def get_str_time (time_ Stamp, str_format= '%y%m%d%h%m '): "" "gets the timestamp, args:time_stamp a 10-bit integer (int) timestamp, such as 1375146861str_format specifies the return format, the value type isString Strrturn: Return format default is month day, July 9, 2013 1:3: 201207090103 "" "Return Time.strftime ("%s "% Str_format, Time.localtime (time _stamp)) def match_cont (Patten, cont): "" "regular match (exact match) args:patten regular expression cont____ match content return:true or False" "" res = Re.match (Patten, cont) if Res:return trueelse:return False def handle_num (Val, ranges= (0, +), Res=list ()): "" Handles pure Numbers "" " val = Int (val) if Val >= ranges[0] and Val <= Ranges[1]:res.append (val) return res def handle_nlist (Val, ranges= (0, 10 0), Res=list ()): "" "handles a list of numbers such as 1,2,3,6" "" Val_list = Val.split (', ') for tmp_val in val_list:tmp_val = Int (tmp_val) if Tmp_val &G t;= Ranges[0] and Tmp_val <= ranges[1]:res.append (tmp_val) return res def Handle_star (Val, ranges= (0, +), res=list ()) : "" Processing asterisk "" "if val = = ' * ': Tmp_val = ranges[0]while tmp_val <= ranges[1]:res.append (tmp_val) tmp_val = Tmp_val + 1return r Es def handle_starnum (Val, ranges= (0, +), Res=list ()): "" "asterisk/number combination such as */3" "" TMP = Val.split ('/') val_step = Int (tmp[1]) if V Al_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, 1 XX), Res=list ()): "" "processing interval such as 8-20" "" TMP = Val.split ('-') range1 = Int (tmp[0]) range2 = Int (tmp[1]) Tmp_val = range1if Range1 &l T 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, +), Res=list ()): "" "Processing interval/step combinations such as 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_s Tepreturn Res def parse_conf (conf, ranges= (0, five), Res=list ()): "" "resolves crontab any one of the time parameters #去除空格, and then splits conf = Conf.strip ( "). Strip (') conf_list = Conf.split (', ') other_conf = []number_conf = []for conf_val in Conf_list:if match_cont (PATTEN[' n Umber '], conf_val): #记Digital Parameters Number_conf.append (conf_val) Else: #记录拆分后纯数字以外的参数, such as wildcard *, Interval 0-8, and 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, or pure numbers coexist with other parameters, the number is used as the time list res = handle_nlist (val= ', '. Join (number_conf), ranges=ranges, res=res) Else: #只有一个纯数字存在, the number is time Interval res = Handle_num (val=number_conf[0], ranges=ranges, Res=res) return res def parse_crontab_time (conf_string): "" " Parse crontab Time configuration Parameters args:conf_string configuration content (total five values: Day and month) range of values minutes: 0-59 hours: 1-23 days: 1-3 January: 1-12 weeks: 0-6 (0 for Sunday) Return:crontab_ran GE list format, time-of-the-time Friday parameters corresponding to the value range "" "Time_limit= ((0), (1, Max), (1, +), (1, Nine), (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 = cin Dex + 1return 0, Crontab_range def time_match_crontab (Crontab_time, time_struct): "" Compares the timestamp to a row of time parameters in the crontab configuration, Determines whether the timestamp is within the configured time range Args:crontab_time____crontab configuration five time (day of the Week) parameter corresponding time value range time_struct____ An integer timestamp, such as: 1375027200 corresponding to the Time-of-day week return:tuple status code, status description "" "CIndex = 0for val in time_struct:if Val not in Crontab_time[cindex]:return 0, Falsecinde x = CIndex + 1return 0, True def close_to_cron (Crontab_time, time_struct): "" "Coron in the specified range (crontab_time) closest to the specified time Time_struc The value of T "" "close_time = Time_structcindex = 0for val_struct in time_struct:offset_min = Val_structval_close = Val_structfor va L_cron in crontab_time[cindex]:offset_tmp = val_struct-val_cronif offset_tmp > 0 and Offset_tmp < Offset_min:val_c lose = 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 "" Gets the time stamp of all points in the value range of the crontab time configuration parameter Args:cron_time match cron The tab configuration specifies all points in time year_num____ specifies the year in which the Limit_start start time rturn:list All points of time, consisting of the time of day and month, e.g. July 29, 2013 18:56:201307291856) "" "#按小时 and minute assembly 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)) #按天 and hour assembly DAY_HM = []for day in cron_time[2]:d ay = str (days) If Len (day) < 2:day =  ' 0%s '% dayfor hour_mnt in hour_minute:day_hm.append ('%s%s '% (day, hour_mnt)) #按月 and days assembly MONTH_DHM = [] #只有30天的月份month_short = [']for ', ' ', ' ', ' ', ' ', ' ' ' ', ' ' One ', ' month in cron_time[3]:month = STR (month) if Len (month) < 2:month = ' 0%s '% monthfor day_hm_s in day_hm:if month = = ' ": if ((not year_num% 4) and (year_num% 1 ) or (not year_num)): #闰年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)) #按年 and months Group  Install 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) #开始时间 \ End time excluding 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:# Exclude Month_dhm_week = []for time_minute in month_dhm_limit:str_time = Time.strptime (Time_minute, '%Y%m%d%H%M%S ') by not specifying the time of week ) if Str_time.tm_wday in Cron_time[4]:month_dhm_week.append (time_minute) return Month_dhm_weekreturn Month_dhm_limit # Crontab timing Parameters Regular Matching Patten = {#纯数字 ' number ': ' ^[0-9]+$ ', #数字列表, such as 1,2,3,6 ' num_list ': ' ^[0-9]+ ([,][0-9]+) +$ ', #星号 * ' star ': ' ^\*$ ', #星号/number combinations such as */3 ' star_num ': ' ^\*\/[0-9]+$ ', #区间 as 8-20 ' range ': ' ^[0-9]+[\-][0-9]+$ ', #区间/step combination such as 8-20/3 ' range_div ': ' ^[0-9]+[\-][0-9]+[\/][0-9]+$ ' #区间/step list combination, e.g. 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): "" "to determine if the match is successful! "" "Try:tips = Tips==none and" File name format error: Job_ month-week-day-time-minute _ filename. 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.dateto String (now, "%y%m%d%h%m00") Time_stamp = Fdatetime.strtotime (now, "%y%m%d%h%m00") #time_stamp = Int (Time.time ()) #解析 Time stamp corresponds to the day of the week_struct = Get_struct_time (time_stamp) match_res = Time_match_crontab (Cron_time, time_struct) return match_res[1]except :p rint Tipsreturn False def main (): "" "Test with Instance" "" #crontab配置中一行时间参数 #conf_string = ' */10 * * * * (CD/OPT/PYTHONPM/DEVPAPPS;/u sr/local/bin/python2.5 data_test.py>>output_error.txt) ' conf_string = ' */10 * * * * ' #时间戳time_stamp = Int (time.time ()) #解析crontab时间配置参数 time-of-day day and month range of values res, desc = parse_crontab_time (conf_string) If res = = 0:cron_time = Descelse:print de Scsys, Exit ( -1) print "\nconfig:", conf_stringprint "\nparse result (range for crontab):" Print "minute:", Cron_time[0]pri NT "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 months week) for%d:"% \ Tim E_stamp, Time_struct #将时间戳与crontab配置中一行时间参数对比, determines whether the timestamp is within the configured time frame 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%d times need to tart-up:\n "% Len ( time_list) Print time_list[:10], ' ... ' if __name__ = = ' __main__ ': #请看 use instance STRs = ' job_@-@-@-@-@_test02.txt.sh ' Print isdo (s TRS) #main () 0 ")
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    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.