Python implementation of parsing crontab configuration file code
Update: June 30, 2014 11:21:53 contribute sth.:junjie
This article introduces the python implementation of the resolution of the crontab configuration file code, can also be said to be the python version of the crontab, the code contains a large number of comments, the need for friends can refer to the following
#/usr/bin/env python #-*- coding:utf-8 -*- """ 1.analyze crontab The five inter-count parameters in the configuration file(ingredient hour date moon weekly),Get their corresponding range of values 2.将hour间戳与crontab配置center一行hour间参数对比,判断该hour间戳是否在配置设定(used form a nominal expression)hour间范围内 """ #$Id $ import re, time, sys from import FDateTime def get_struct_time(time_stamp_int): """ 按整型hour间戳gainspecification化hour间 ingredient hour date moon weekly Args: time_stamp_int 为传入value of为hour间戳(plastic surgery),as if:1332888820 go throughlocaltimeConverted to 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____come (or go) back ingredient hour date moon weekly """ st_time = (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): """Get from string 整型hour间戳 Args: time_str string (computer science)类型(used form a nominal expression)hour间戳 as if '31/Jul/2013:17:46:01' str_format indicate clearly and with certainty time_str formats as if '%d/%b/%Y:%H:%M:%S' Return: come (or go) back10bitwise integer(int)hour间戳,as if 1375146861 """ return int(((time_str, str_format))) def get_str_time(time_stamp, str_format='%Y%m%d%H%M'): """ gainhour间戳, Args: time_stamp 10bitwise integer(int)hour间戳,as if 1375146861 str_format indicate clearly and with certaintycome (or go) backspecification,The value type is string (computer science) str Rturn: come (or go) backspecification default surname Nianmoondatehouringredient,as if2013surname Nian7moon9date1hour3ingredient :201207090103 """ return ("%s" % str_format, (time_stamp)) def match_cont(patten, cont): """ regular match(exact match) Args: patten regular expression (math.) cont____ Matching content Return: True or False """ res = (patten, cont) if res: return True else: return False def handle_num(val, ranges=(0, 100), res=list()): """Handling pure numbers""" val = int(val) if val >= ranges[0] and val <= ranges[1]: (val) return res def handle_nlist(val, ranges=(0, 100), res=list()): """Handle lists of numbers such as 1,2,3,6.""" val_list = (',') for tmp_val in val_list: tmp_val = int(tmp_val) if tmp_val >= ranges[0] and tmp_val <= ranges[1]: (tmp_val) return res def handle_star(val, ranges=(0, 100), res=list()): """Handle the asterisk.""" if val == '*': tmp_val = ranges[0] while tmp_val <= ranges[1]: (tmp_val) tmp_val = tmp_val + 1 return res def handle_starnum(val, ranges=(0, 100), res=list()): """Asterisk/number combinations such as */3""" tmp = ('/') val_step = int(tmp[1]) if val_step < 1: return res val_tmp = int(tmp[1]) while val_tmp <= ranges[1]: (val_tmp) val_tmp = val_tmp + val_step return res def handle_range(val, ranges=(0, 100), res=list()): """Processing interval e.g. 8-20""" tmp = ('-') range1 = int(tmp[0]) range2 = int(tmp[1]) tmp_val = range1 if range1 < 0: return res while tmp_val <= range2 and tmp_val <= ranges[1]: (tmp_val) tmp_val = tmp_val + 1 return res def handle_rangedv(val, ranges=(0, 100), res=list()): """Processing interval/step combination e.g. 8-20/3""" tmp = ('/') 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 res val_tmp = val_start while val_tmp <= val_end and val_tmp <= ranges[1]: (val_tmp) val_tmp = val_tmp + val_step return res def parse_conf(conf, ranges=(0, 100), res=list()): """Parsing any of crontab's five time parameters.""" # Remove spaces and split again conf = (' ').strip(' ') conf_list = (',') other_conf = [] number_conf = [] for conf_val in conf_list: if match_cont(PATTEN['number'], conf_val): # Record split purely numeric parameters number_conf.append(conf_val) else: # Record parameters other than pure numbers after splitting, such as wildcards *, intervals 0-8, and 0-8/3, etc. other_conf.append(conf_val) if other_conf: #Handles a variety of parameters other than purely digital for conf_val in other_conf: for key, ptn in (): 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: # pure numbers more than 1, or pure numbers coexist with other parameters, then the numbers are used as a time list res = handle_nlist(val=','.join(number_conf), ranges=ranges, res=res) else: #If only one pure number exists, then 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): """ analyzecrontabhour间配置参数 Args: conf_string Configuration content(Five values in total:ingredient hour date moon weekly) range of values ingredient钟:0-59 小hour:1-23 date期:1-31 moon份:1-12 last week:0-6(0表示weeklydate) Return: crontab_range listspecification,ingredient hour date moon weekly 五个传入参数ingredient别对应(used form a nominal expression)range of values """ time_limit = ((0, 59), (1, 23), (1, 31), (1, 12), (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: (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]' % conf_string crontab_range.append(res_conf) cindex = cindex + 1 return 0, crontab_range def time_match_crontab(crontab_time, time_struct): """ Compare the timestamp with the time parameter on a line in the crontab configuration to determine if the timestamp is within the time range set by the configuration Args. crontab_time____crontab configuration of the five time (minutes, hours, days, months, weeks) parameter corresponding to the range of time values time_struct____ An integer timestamp, e.g., 1375027200 corresponding to minutes, hours, days, months, weeks. Return. tuple status code, status description """ cindex = 0 for val in time_struct: if val not in crontab_time[cindex]: return 0, False cindex = cindex + 1 return 0, True def close_to_cron(crontab_time, time_struct): """coron(used form a nominal expression)indicate clearly and with certainty范围(crontab_time)center closest indicate clearly and with certaintyhour间 time_struct value of""" close_time = time_struct cindex = 0 for val_struct in time_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 = offset_tmp close_time[cindex] = val_close cindex = cindex + 1 return close_time def cron_time_list( cron_time, year_num=int(get_str_time((), "%Y")), limit_start=get_str_time((), "%Y%m%d%H%M"), limit_end=get_str_time(() + 86400, "%Y%m%d%H%M") ): #print "\nfrom ", limit_start , ' to ' ,limit_end """ gaincrontabhour间配置参数range of values内(used form a nominal expression)所有hour间点 (used form a nominal expression) hour间戳 Args: cron_time in line withcrontab配置indicate clearly and with certainty(used form a nominal expression)所有hour间点 year_num____indicate clearly and with certainty在哪一surname Nian内 gain limit_start 开始hour间 Rturn: List 所有hour间点组成(used form a nominal expression)列表(surname Nianmoondatehouringredient 组成(used form a nominal expression)hour间,as if2013surname Nian7moon29date18hour56ingredient:201307291856) """ # Assembled by the hour and minute 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)) # Assembled by day and hour day_hm = [] for day in cron_time[2]: day = str(day) if len(day) < 2: day = '0%s' % day for hour_mnt in hour_minute: day_hm.append('%s%s' % (day, hour_mnt)) # Assembled by month and day month_dhm = [] # Months with only 30 days month_short = ['02', '04', '06', '09', '11'] 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 == '02': if (((not year_num % 4 ) and (year_num % 100)) or (not year_num % 400)): #Leap year February has 29 days if int(day_hm_s[:2]) > 29: continue else: # Other Februarys have 28 days 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)) # Assembled by year and month 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) # Exclusions other than start time \ end time if (int(time_ymdhm[:len_start]) < int(limit_start)) or \ (int(time_ymdhm[:len_end]) > int(limit_end)): continue month_dhm_limit.append(time_ymdhm) if len(cron_time[4]) < 7: # Exclusions by not being at the designated time of the week month_dhm_week = [] for time_minute in month_dhm_limit: str_time = (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 Regular matching for various ways of writing #crontab time parameters. PATTEN = { # Pure numbers 'number':'^[0-9]+$', #A list of numbers, such as 1,2,3,6. 'num_list':'^[0-9]+([,][0-9]+)+$', # Asterisk * 'star':'^\*$', # Asterisk/number combinations, e.g. */3 'star_num':'^\*\/[0-9]+$', # Intervals such as 8-20 'range':'^[0-9]+[\-][0-9]+$', # Interval/step combination e.g. 8-20/3 'range_div':'^[0-9]+[\-][0-9]+[\/][0-9]+$' # Interval/step list combinations, e.g. 8-20/3,21,22,34 #'range_div_list':'^([0-9]+[\-][0-9]+[\/][0-9]+)([,][0-9]+)+$' } # Handling of each canonical counterpart 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): """ Determine if the match was successful! """ try: tips = tips==None and "File name format error: job_month-week-day-hour-minute_filename.txt" or tips timer = ('@',"*").replace('%','/').split('_')[1] month,week,day,hour,mins = ('-') conf_string = mins+" "+hour+" "+day+" "+month+" "+week res, desc = parse_crontab_time(conf_string) if res == 0: cron_time = desc else: return False now =() now = (now, "%Y%m%d%H%M00") time_stamp = (now, "%Y%m%d%H%M00") #time_stamp = int(()) # parsing timestamps corresponding to minutes, hours, days, months, weeks. time_struct = get_struct_time(time_stamp) match_res = time_match_crontab(cron_time, time_struct) return match_res[1] except: print tips return False def main(): """Examples for testing""" #crontab configuration with one line time parameter #conf_string = '*/10 * * * * (cd /opt/pythonpm/devpapps; /usr/local/bin/python2.5 data_test.py>>output_error.txt)' conf_string = '*/10 * * * *' #Timestamp time_stamp = int(()) # Analyze crontab time configuration parameters minute hour day month week each value range res, desc = parse_crontab_time(conf_string) if res == 0: cron_time = desc else: print desc sys, exit(-1) print "\nconfig:", conf_string print "\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] # parsing timestamps corresponding to minutes, hours, days, months, weeks. 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 of a line in the crontab configuration to determine if the timestamp is within the time range set in the configuration match_res = time_match_crontab(cron_time, time_struct) print "\nmatching result:", match_res #crontab configures a set of time stamps for the most recent proximity in the set range 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__': # See examples of use strs = 'job_@-@-@-@-@_test02.' print isdo(strs) #main()0")
Related articles
Microsoft open source the strongest Python automation artifact Playwright (without writing a line of code)
This article introduces the Microsoft open source the strongest Python automation artifact Playwright (without writing a line of code), the text through the sample code is very detailed, for everyone to learn or work with a certain reference learning value, the need for friends below with the editorial to learn together!2021-01-01Script performance analysis in python
This article introduces the script performance analysis in python, with good reference value, I hope to help you. If there is any error or not fully considered, please do not hesitate to give advice!2022-11-11python make magnet search tool
This article mainly introduces how to use python to create a magnetic search tool, to help you better understand and learn to use python, interested parties can understand the following2021-03-03python drawing - output the color value of the specified pixel point method
Today I'm going to share a python drawing - output the color value of the specified pixel point method, has a good reference value, I hope to help you. Together follow the editor over to see it2019-07-075 Bad Habits Programmers Have When Writing Python, How Many Do You Have?
This post is about 5 bad habits of programmers when writing Python, how many do you have? Some habits will make the bugs become hidden and difficult to track, of course, there are also some are not wrong, just personally feel not elegant enough. This article has sample code, interested friends follow the editor to take a look together!2018-11-11Matplotlib graphing in one article!
Matplotlib is a Python-based plotting library, which provides a similar set of commands with Matlab API, very suitable for interactive drawing, this article introduces the Matplotlib graphic drawing information, you can refer to the next!2023-09-09Pygame Surface implementation for creating images
This article introduces the realization of Pygame Surface to create an image, the text through the sample code is very detailed, with certain reference value, interested partners can refer to a2022-02-02Tensorflow does not support AVX2 instruction set solution
Today, I'd like to share a Tensorflow does not support the AVX2 instruction set of the solution, has a good reference value, I hope to help you. Together follow the editor over to see it2020-02-02Python development tools PyCharm download and install step-by-step graphic tutorials
This article introduces the Python development tools PyCharm download and install step-by-step graphic tutorials, there is a need for friends can refer to reference, I hope to be able to help, I wish you more progress, an early promotion and salary increase!2023-07-07Python Sanic framework for file uploads
Sanic is a Python 3.5 + asynchronous Web framework, its design concept is similar to Flask, but using a more efficient asynchronous I/O processing, in dealing with file uploads, Sanic also provides a convenient and efficient way to this tutorial will be combined with a practical case , a detailed introduction to how to implement the file upload function in the Sanic framework, friends in need can reference2024-08-08