The parse crontab configuration file code implemented by Python _python

Source: Internet
Author: User
Tags ranges time interval
#/usr/bin/env python #-*-coding:utf-8-*-"" "1. Resolves five parameters (time-sharing and eclipses) in the crontab configuration file to obtain their corresponding range of 2. One row of time parameters in the timestamp and crontab configuration Compare to determine if the timestamp is within the configured time range "" "# $Id $ import Re, time, sys from Core.FDateTime.FDateTime import fdatetime def get_struct 
		_time (Time_stamp_int): "" "to get the formatted time by the integer timestamp args:time_stamp_int for the passed value of time stamp (shaping), such as: 1332888820 after localtime conversion 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 the Week "" "St_time = Time.localtime (time_stamp_int) returns [St_time.tm_min, St_time.tm_ho
		ur, st_time.tm_mday, St_time.tm_mon, St_time.tm_wday] def get_strptime (Time_str, Str_format): "" To get an integral timestamp from a string Args: Time_str String type timestamp such as ' 31/jul/2013:17:46:01 ' str_format specifies TIME_STR format such as '%d/%b/%y:%h:%m:%s ' return: Returns 10-bit int (int) time Stamp, such as 1375146861 "" "Return Int (Time.mktime (Time.strptime (Time_str, Str_format)) def get_str_time (Time_stamp, Str_forma t= '%y%m%d%h%m '): "" "GetTimestamp, Args:time_stamp 10-bit integer (int) timestamp, such as 1375146861 str_format specifies the return format, and the value type is String str rturn: The return format defaults to date of year, such as July 9, 2013 1 O'Clock 
	3 points: 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____ matching content return:true or False" "res = Re.match (Patten, cont) if 
	Res:return True Else:return False def handle_num (Val, ranges= (0), Res=list ()): "" Processing pure digits "" val = Int (val) If Val >= ranges[0] and Val <= ranges[1]: Res.append (val) return res def handle_nlist (Val, ranges= (0), R Es=list ()): "" To process 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 >= 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), Res=list ()): "" "" "asterisk/number combination such as */3" "" TMP = Val.split ('/') val_step = Int (tmp[1]) if Val_step < 1:return res val_tmp = Int (tmp[1]) while Val_tmp <= ranges[1]: res.append (val_t MP) Val_tmp = val_tmp + val_step return res def handle_range (Val, ranges= (0), Res=list ()): "" "" "processing interval such as 8-20" "" t MP = Val.split ('-') range1 = Int (tmp[0]) range2 = Int (tmp[1]) Tmp_val = Range1 if Range1 < 0:return res while T Mp_val <= range2 and Tmp_val <= ranges[1]: res.append (tmp_val) tmp_val = tmp_val + 1 return res def Handle_ra Ngedv (Val, ranges= (0), Res=list ()): "" "Processing interval/step combinations such as 8-20/3" "" TMP = Val.split ('/') Range2 = Tmp[0].split ('-') VA
		L_start = Int (range2[0]) val_end = Int (range2[1]) val_step = Int (tmp[1]) if (Val_step < 1) or (Val_start < 0): return res val_tmp = Val_start while val_tmp <= val_end and Val_tmp <= ranges[1]: res.append (val_tmp) val_tmp = val_tmp + Val_step reTurn res def parse_conf (conf, ranges= (0), Res=list ()): "" "to resolve any of the crontab five time parameters," "#去除空格, and then split the conf = Conf.strip ( "). Strip (') conf_list = Conf.split (', ') other_conf = [] number_conf = [] for conf_val in Conf_list:if Match_con T (patten[' number '], conf_val): #记录拆分后的纯数字参数 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 P Atten.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 a pure number coexisting with other parameters, the number as the time list res = handle_nlist (val= ', '. Jo In (number_conf), ranges=ranges, res=res) Else: #只有一个纯数字存在, the number is a time interval res = Handle_num (val=number_conf[0), Ranges=ra Nges, Res=res) return res def parse_crontab_time (conf_string): "" "Parsing crontab time configuration Parameters args:conf_string configuration content (Total five values: min Time and Moon Week) value range min: 0-59 Hours: 1-23 Days: 1-3 January: 1-12 weeks: 0-6 (0 for Sunday) return:crontab_range list format, time of day and the moon Friday an incoming parameter corresponds to the value range "" "Time_limit = (0  , (1), (1), (1,), (0, 6)) Crontab_range = [] CList = [] Conf_length = 5 Tmp_list = Conf_string.split (' ') for Val in Tmp_list:if len (clist) = = Conf_length:break if Val:clist.append (val) If Len (clist)!= conf  _length:return-1, ' config error whith [%s] '% conf_string cindex = 0 for 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] '% CO Nf_string crontab_range.append (res_conf) CIndex = cindex + 1 return 0, Crontab_range def time_match_crontab (crontab _time, Time_struct): "" To compare the timestamp with a row of time parameters in the Crontab configuration to determine whether the timestamp is within the configured time range Args:crontab_time____crontab Five of the time in the configuration (time-sharing and lunar weeks) Parameter corresponding time range time_struct____ an integral time stamp, such as: 1375027200 corresponding time-sharing and return:tuple state code, status description "" "CIndex = 0 for Val in Tim E_struct:if Val Not IN Crontab_time[cindex]: return 0, False cindex = cindex + 1 return 0, True def close_to_cron (Crontab_time, Time_st ruct): "" "Coron Specified range (crontab_time) the value closest to the specified time Time_struct" "" close_time = time_struct cindex = 0 for val_struct in t Ime_struct:offset_min = val_struct Val_close = val_struct for Val_cron in Crontab_time[cindex]: Offset_tmp = val _struct-val_cron if offset_tmp > 0 and offset_tmp < Offset_min:val_close = Val_struct Offset_min = off Set_tmp Close_time[cindex] = val_close CIndex = cindex + 1 return close_time def cron_time_list (Cron_time, yea R_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 ' "" Get crontab Time configuration parameter values range All point-in-time timestamp Args:cron_time compliant with the crontab configuration specifies all the Point-in-time year_num____ specify in which year to get the Limit_start start time rturn:list all the point-in-time lists (The time of the month and date, such as July 29, 2013 18 o'clock 56 points: 201307291856) "" "#按小时 and minute assembly Hour_minute = [] for minute in cron_time[0]: minute = str (minute) If Len (minute) < 2:minute = ' 0%s '% minute for hour in cron_time[1]: hour = str (hour) If Len (hour) < 2:hour = ' 0%s '% hour hour_minute.append ('%s%s '% (hour, minute)) #按天 and hour assembly DAY_HM = [] for days in cron_time[2]: day = str (day If Len (day) < 2:day = ' 0%s '%/hour_mnt in Hour_minute:day_hm.append ('%s%s '% (day, hour_mnt)) #按 Month and day assembly MONTH_DHM = [] #只有30天的月份 month_short = [', ', ', ', ', ', ', ', ', ', ', '] for month in cron_time[3]: month = str (month) If Len (month) < 2:month = ' 0%s '% month for day_hm_s in day_hm:if month = ' * ': if ((not) _num% 4) and (year_num%)) or (not year_num%)): #闰年2月份有29天 if int (day_hm_s[:2]) > 29:contin UE else: #其它2月份有28天 if int (day_hm_s[:2]) > 28:continue if month in Month_short:if Int (day_
					Hm_s[:2]) > 30:Continue Month_dhm.append ('%s%s '% (month, day_hm_s)) #按年 and monthly assembly 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 Exclude if (int (Time_ymdhm[:len_start]) < int (limit_start)) or \ (int (time_ymdhm[:len_end)) > int (limit_end)): C Ontinue Month_dhm_limit.append (TIME_YMDHM) If Len (Cron_time[4]) < 7: #按不在每周指定时间的排除 Month_dhm_week = [] for Tim E_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_week return month_dhm_limit a regular match #crontab时间参数各种写法 PAT TEN = {#纯数字 ' number ': ' ^[0-9]+$ ', #数字列表, such as 1,2,3,6 ' num_list ': ' ^[0-9]+ ([,][0-9]+) +$ ', #星号 * ' star ': ' ^\*$ ', #星号/number combination , such as */3 ' star_num ': ' ^\*\/[0-9]+$ ', #区间 such 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, such as 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 ': hand
	Le_range, ' Range_div ': Handle_rangedv} def isdo (strs,tips=none): "" "to determine whether the match is successful! "" "Try:tips = Tips==none and" File name format error: Job_ month-week-day-time-minute _ filename. txt "or tips timer = strs.replace (' @ ', ' * '). Replace ('% ', '/') ). split ('_') [1] month,week,day,hour,mins = Timer.split ('-') conf_string = mins+ "" +hour+ "" +day+ "" +month+ "" +week R ES, desc = parse_crontab_time (conf_string) If res = = 0:cron_time = desc Else:return False now =FDATETIME.N ow () now = Fdatetime.datetostring (now, "%y%m%d%h%m00") Time_stamp = Fdatetime.strtotime (now, "%y%m%d%h%m00") #ti me_stamp = Int (Time.time ()) #解析 timestamp corresponding to the time interval time_struct = Get_struct_time (time_stamp) match_res = TIME_MATCH_CR Ontab (Cron_time, time_struct) return match_res[1] Except:prinT tips return False def main (): "" "" "#crontab配置中一行时间参数 #conf_string = ' */10 * * * * * (CD/OPT/PYTHONPM/DEVPAP ps /usr/local/bin/python2.5 data_test.py>>output_error.txt) ' conf_string = ' */10 * * * ' #时间戳 time_stamp = Int (time . Time ()) #解析crontab时间配置参数 value range Res desc = parse_crontab_time (conf_string) If res = d ESC else:print DESC sys, exit ( -1) print "\nconfig:, conf_string print" \nparse result (range for crontab): "P 
	Rint "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] #解析 timestamp corresponding to the time of the week time_struct = Get_struct_time (time_stamp) print "\nstruct Tim E (minute hour day month week) for%d: "% \ Time_stamp, time_struct #将时间戳与crontab配置中一行时间参数对比 to determine whether the timestamp is within the configured time range MA Tch_res = Time_match_crontab (Cron_time, time_struct) print "\nmatching result:", Match_res #crontab配置设定范围中最近接近时指定间戳的一组 Time Most_close = CloSe_to_cron (Cron_time, time_struct) print "\nin range of crontab time which are 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__ ': #请看 usages strs = ' job_@-@-@-@-@_test02.txt.sh ' Print isdo (STRs) #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.