This article mainly introduces the code for parsing the crontab configuration file implemented by python. It can also be called the crontab of python. the code contains a large number of comments. For more information, see
#/Usr/bin/env python #-*-coding: UTF-8-*-"" 1. parse the five parameters in the crontab configuration file (by hour, day, month, week) and obtain their corresponding value range 2. compare the timestamp with the time parameter in the crontab configuration to determine whether the timestamp is "# $ Id $ import re, time, sysfrom Core within the configured time range. FDateTime. FDateTime import FDateTime def get_struct_time (time_stamp_int): "" Get the formatted time point by integer timestamp. the Args: time_stamp_int indicates that the input value is the timestamp (integer), for example: 1332888820 after localtime conversion, it becomes time. struct_time (maid = 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 minutes, days, months, weeks "st_time = time. localtime (time_stamp_int) return [st_time.tm_min, hour, st_time.tm_mday, st_time.tm_mon, hour] def get_strptime (time_str, str_format): "Get integer time stamp Args from string: time_str string timestamp, such as '31/Jul/2013: 17: 46: 01 'str _ format, specifies the format of time_str, such as' % d/% B/% Y: % H: % M: % s' Return: returns a 10-bit integer (int) timestamp, such as 1375 146861 "" return int (time. mktime (time. strptime (time_str, str_format) def get_str_time (time_stamp, str_format = '% Y % m % d % H % M'): "get timestamp, Args: time_stamp: a 10-bit integer (int) Timestamp. for example, 1375146861str_format indicates the return format. The value type is string strRturn. The return format is year, month, and day by default, for example, 01:03, January 1, 201207090103. strftime ("% s" % str_format, time. localtime (time_stamp) def match_cont (patten, cont): "" regular match (exact match) Args: patten regular expression cont ____ matched content Return: True or False "" res = re. match (patten, cont) if res: return Trueelse: return False def handle_num (val, ranges = (0,100), res = list ()): "processing pure numbers" 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 (): "processing number lists such as 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 (): "" processing asterisk "if val = '*': tmp_val = ranges [0] while tmp_val <= ranges [1]: res. append (tmp_val) tmp_val = tmp_val + 1 return res def handle_starnum (val, ranges = (0,100), res = list ()): "asterisk/number combination, such as */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 ()): "processing interval such as 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 + 1 return res def handle_rangedv (val, ranges = (0,100), res = list (): "" processing interval/step size For example, 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 ()): "parse any of the five time parameters of crontab" "# Remove spaces and then split the 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 ): # record the split-up numeric parameter number_conf.append (conf_val) else: # Record parameters other than pure numbers after split, such as wildcard *, range 0-8, and other_conf.append (conf_val) such as 0-8/3 if other_conf: # process parameters other than pure numbers 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: # more pure numbers than 1, or the pure number and other parameters coexist, the number is used as the Time list res = handle_nlist (val = ','. join (number_conf), ranges = ranges, res = res) else: # Only one pure number exists, and the number is the 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 parameter Args: conf_string configuration content (five values in total: minutes: 0-59 hours: 1- 23 date: 1-31 month: 1-12 weeks: 0-6 (0 indicates Sunday) Return: crontab_range list format, the values of the input parameters corresponding to the hour, day, month, and week are as follows: "" 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 + 1 return 0, crontab_range def time_match_crontab (crontab_time, time_struct): "" compares the timestamp with the time parameter in crontab configuration to determine whether the timestamp is configured In the specified time range, Args: crontab_time ____ the five time (hour, day, month, week) parameters in the crontab configuration correspond to the time value range time_struct ____ an integer timestamp, such: 1375027200 Return: tuple status code, status description "cindex = 0for val in time_struct: if val not in crontab_time [cindex]: return 0, falsecindex = cindex + 1 return 0, True def close_to_cron (crontab_time, time_struct): "" specified range of coron (crontab_time) "" close_time = time_structcindex = 0for val_st Ruct in time_struct: offset_min = bytes = 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 + 1 return close_time def cron_time_list (cron_time, year_num = int (get_str_time. time (), "% Y"), limit_start = get_str_time (time. t Ime (), "% 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 timestamp Args of all time points within the value range of the crontab Time configuration parameter: cron_time: all time points specified in the crontab configuration year_num ____ specify the year in which the limit_start start time Rturn: List a List composed of all time points (time composed of year, month, day, for example, July 29, 2013: 201307291856) "# assemble hour_minute = [] for minute in cron_time [0]: minute = str (minute) by hour and minute) if len (minute) <2: min Ute = '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 )) # assemble 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 )) # assemble month_dhm = [] # 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): #29 days in February of the year if int (day_hm_s [: 2])> 29: continueelse: # Other February 28 days 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) # assemble len_start = len (limit_star T) 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) # exclude if (int (time_ymdhm [: len_start]) <int (limit_start) or \ (int (time_ymdhm [: len_end])> int (limit_end): Interval (time_ymdhm) if len (cron_time [4]) <7: # exclude month_dhm_week = [] for time_minute in month_dhm_limit from the specified time of the week: 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 # Regular expression PATTEN = {# pure number 'number': '^ [0-9] + $', # number list, such as 1, 2, 3, 6 'Num _ list': '^ [0-9] + ([,] [0-9] +) + $', # asterisk * 'start ': '^ \ * $', # asterisk/number combination, such as */3 'star _ num':' ^ \ * \/[0-9] + $ ', # range: 8-20 'range': '^ [0-9] + [\-] [0-9] + $ ', # range/step combination, for example, 8-20/3 'range _ p': '^ [0-9] + [\-] [0-9] + [\/] [0 -9] + $ '# range/step list combination, such as 8-20/3, 34 # 'range _ p_list ': '^ ([0-9] + [\-] [0-9] + [\/] [0-9] +) ([,] [0-9] +) + $ '} # processing method for each regular expression PATTEN_HANDLER = {'number': handle_num, 'Num _ list': handle_nlist, 'Star ': handle_star, 'Star _ num': handle_starnum, 'range': handle_range, 'range _ p': handle_rangedv} def isdo (strs, tips = None ): "determines whether the match is successful! "Try: tips = None and" file name format error: job_month-week-day-hour-minute _ file name .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] hour t: print tipsreturn False def main (): "test instance" # A time parameter in crontab configuration # conf_string = '*/10 *** (cd/opt/pythonpm/devpapps; /usr/local/bin/python2.5 data_test.py> output_error.txt) 'conf _ string = '*/10 ***' # timest_stamp = int (time. time () # parse crontab time configuration parameters by hour, day, month, and week value range 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 # compare the timestamp with the time parameter in crontab configuration to determine whether the timestamp is within the configured time range match_res = time_match_crontab (cron_time, time_struct) print "\ nmatching result:", match_res # 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 the instance strs = 'job_@-@-@-@_test02.txt. sh 'print isdo (strs) # main () 0 ")