Parse the crontab configuration file using python

Source: Internet
Author: User

Parse the crontab Configuration File Code implemented by python.

I personally feel good when I use python to operate the crontab Task Plan script.
#/Usr/bin/env python
#-*-Coding: UTF-8 -*-

"""
1. parse the five parameters in the crontab configuration file (by hour, day, month, and week) to obtain their corresponding value range.
2. Compare the timestamp with the time parameter in the crontab configuration to determine whether 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 ):
"""
Obtain the formatted time, hour, day, month, and week by integer timestamp.
Args:
Time_stamp_int indicates the input value as the timestamp (integer), for example, 1332888820.
After localtime conversion
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 ____ returns the week, day, month, and 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 ):
"Get integer timestamp from string
Args:
Time_str string timestamp, for example, '31/Jul/2013: 17: 46: 01'
Str_format specifies the format of time_str, for example, '% 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 '):
"""
Obtain the timestamp,
Args:
Time_stamp 10-bit integer (int) timestamp, such as 1375146861
Str_format specifies the return format. The value type is string str.
Rturn:
The default format is year, month, day, for example, July 9, 2013 01:03: 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 ____ matched content
Return:
True or False
"""
Res = re. match (patten, cont)
If res:
Return True
Else:
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 asterisks """
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 res
Val_tmp = int (tmp [1])
While val_tmp <= ranges [1]:
Res. append (val_tmp)
Val_tmp = val_tmp + val_step
Return res

Def handle_range (val, ranges = (0,100), res = list ()):
"Processing range, for example, 8-20 """
Tmp = val. split ('-')
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]:
Res. append (tmp_val)
Tmp_val = tmp_val + 1
Return res

Def handle_rangedv (val, ranges = (0,100), res = list ()):
"Processing interval/step combination, 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 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,100), res = list ()):
"Resolve any of the five time parameters of crontab """
# Remove spaces and then split
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 numeric parameters
Number_conf.append (conf_val)
Else:
# Record parameters other than pure numbers after split, such as wildcard *, range 0-8, and 0-8/3
Other_conf.append (conf_val)
If other_conf:
# Processing parameters other than numbers only
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:
# If the number is greater than 1, or the number coexist with other parameters, the number is used as the time list.
Res = handle_nlist (val = ','. join (number_conf), ranges = ranges, res = res)
Else:
# If only one pure number exists, 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 parameters
Args:
Conf_string configuration content (five values in total: hour, day, month, week)
Value Range: minute: 0-59 hour: 1-23 Date: 1-31 month: 1-12 week: 0-6 (0 indicates Sunday)
Return:
Crontab_range list format. The value range of the input parameters, namely, hour, month, and week.
"""
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:
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] '% 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 in the crontab configuration to determine whether the timestamp is within the configured time range.
Args:
Crontab_time ____ the time value range of the five time (hour, day, month, week) parameter in crontab Configuration
Time_struct ____ a timestamp of an integer, for example, the hour, day, month, and week corresponding to 1375027200
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's specified range (crontab_time) is closest to the value of time_struct at the specified time """
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 (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
"""
Obtain the timestamp of all time points within the value range of the crontab time Configuration Parameter
Args:
Cron_time: All time points specified by crontab Configuration
Year_num ____ specifies which year to obtain
Limit_start Start Time
Rturn:
List a List Of all time points (Time composed by year, month, and day) (www.jbxue.com), for example, January 1, July 29, 2013: 201307291856)
"""
# Assembly by 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 ))
# Assembly 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 ))
# Monthly and daily assembly
Month_dhm = []
# Only 30 days of the month
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 )):
#29 days in March of the leap year
If int (day_hm_s [: 2])> 29:
Continue
Else:
#28 days for other February
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 ))
# Assembly 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)
# Exclude from 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:
# Exclude from the specified time per week
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_week
Return month_dhm_limit


# Regular Expression matching of crontab time parameters
PATTEN = {
# Pure numbers
'Number': '^ [0-9] + $ ',
# Number list, such as 1, 2, 3, 6
'Num _ list': '^ [0-9] + ([,] [0-9] +) + $ ',
# Asterisk *
'Star': '^ \ * $ ',
# Asterisk/digit combination, for example, */3
'Star _ num': '^ \ * \/[0-9] + $ ',
# Range: 8-20
'Range': '^ [0-9] + [\-] [0-9] + $ ',
# Range/step combination, for example, 8-20/3
'Range _ div ':' ^ [0-9] + [\-] [0-9] + [\/] [0-9] + $'
# Range/step list combination, such as 8-20/3, 34
# 'Range _ div_list ':' ^ ([0-9] + [\-] [0-9] + [\/] [0-9] +) ([,] [0-9] +) + $'
}
# Handling methods for each regular expression
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 ):
"""
Check whether the matching is successful!
"""
Try:
Tips = None and "file name format error: job_--shar_file name .txt" or tips
Timer = strs. replace ('@', "*"). replace ('%', '/'). split ('_') [1]
Month, week, day, hour, mins = timer. split ('-')
Conf_string = mins + "" + hour + "" + day + "" + month + "" + week
Res, desc = parse_crontab_time (conf_string)
If res = 0:
Cron_time = desc
Else:
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 ())
# Minute, day, month, and week corresponding to the parsing Timestamp
Time_struct = get_struct_time (time_stamp)
Match_res = time_match_crontab (cron_time, time_struct)
Return match_res [1]
Except t:
Print tips
Return False

Def main ():
"Test instance """
# Crontab Configuration
# 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 (time. time ())

# Resolve crontab time configuration parameters by hour, day, month, and week 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]

# Minute, day, month, and week corresponding to the parsing Timestamp
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 the 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

# Crontab configuration specifies a set of Timestamp time when the closest to the specified timestamp 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 % d times need to tart-up: \ n" % len (time_list)
Print time_list [: 10], '...'

If _ name _ = '_ main __':
# See instances
Strs = 'job_@-@-@-@-@_test02.txt. Sh'
Print isdo (strs)

# Main () 0 ")

Related Article

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.