欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python實現(xiàn)的解析crontab配置文件代碼

 更新時間:2014年06月30日 11:21:53   投稿:junjie  
這篇文章主要介紹了python實現(xiàn)的解析crontab配置文件代碼,也可以說是python版的crontab,代碼中包含大量注釋,需要的朋友可以參考下
#/usr/bin/env python
#-*- coding:utf-8 -*-
 
"""
1.解析 crontab 配置文件中的五個數(shù)間參數(shù)(分 時 日 月 周),獲取他們對應(yīng)的取值范圍
2.將時間戳與crontab配置中一行時間參數(shù)對比,判斷該時間戳是否在配置設(shè)定的時間范圍內(nèi)
"""
 
#$Id $
 
import re, time, sys
from Core.FDateTime.FDateTime import FDateTime
 
def get_struct_time(time_stamp_int):
	"""
	按整型時間戳獲取格式化時間 分 時 日 月 周
	Args:
		time_stamp_int 為傳入的值為時間戳(整形),如:1332888820
		經(jīng)過localtime轉(zhuǎn)換后變成
		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____返回 分 時 日 月 周
	"""
 
	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):
	"""從字符串獲取 整型時間戳
	Args:
		time_str 字符串類型的時間戳 如 '31/Jul/2013:17:46:01'
		str_format 指定 time_str 的格式 如 '%d/%b/%Y:%H:%M:%S'
	Return:
		返回10位整型(int)時間戳,如 1375146861
	"""
	return int(time.mktime(time.strptime(time_str, str_format)))
 
def get_str_time(time_stamp, str_format='%Y%m%d%H%M'):
	"""
	獲取時間戳,
	Args:
		time_stamp 10位整型(int)時間戳,如 1375146861
		str_format 指定返回格式,值類型為 字符串 str
	Rturn:
		返回格式 默認為 年月日時分,如2013年7月9日1時3分 :201207090103
	"""
	return time.strftime("%s" % str_format, time.localtime(time_stamp))
 
def match_cont(patten, cont):
	"""
	正則匹配(精確符合的匹配)
	Args:
		patten 正則表達式
		cont____ 匹配內(nèi)容
	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()):
	"""處理純數(shù)字"""
	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()):
	"""處理數(shù)字列表 如 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()):
	"""處理星號"""
	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()):
	"""星號/數(shù)字 組合 如 */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()):
	"""處理區(qū)間 如 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()):
	"""處理區(qū)間/步長 組合 如 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()):
	"""解析crontab 五個時間參數(shù)中的任意一個"""
	#去除空格,再拆分
	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):
			#記錄拆分后的純數(shù)字參數(shù)
			number_conf.append(conf_val)
		else:
			#記錄拆分后純數(shù)字以外的參數(shù),如通配符 * , 區(qū)間 0-8, 及 0-8/3 之類
			other_conf.append(conf_val)
	if other_conf:
		#處理純數(shù)字外各種參數(shù)
		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:
			#純數(shù)字多于1,或純數(shù)字與其它參數(shù)共存,則數(shù)字作為時間列表
			res = handle_nlist(val=','.join(number_conf), ranges=ranges, res=res)
		else:
			#只有一個純數(shù)字存在,則數(shù)字為時間 間隔
			res = handle_num(val=number_conf[0], ranges=ranges, res=res)
	return res
 
def parse_crontab_time(conf_string):
	"""
	解析crontab時間配置參數(shù)
	Args:
		conf_string  配置內(nèi)容(共五個值:分 時 日 月 周)
					 取值范圍 分鐘:0-59 小時:1-23 日期:1-31 月份:1-12 星期:0-6(0表示周日)
	Return:
	crontab_range	 list格式,分 時 日 月 周 五個傳入?yún)?shù)分別對應(yīng)的取值范圍
	"""
	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):
	"""
	將時間戳與crontab配置中一行時間參數(shù)對比,判斷該時間戳是否在配置設(shè)定的時間范圍內(nèi)
	Args:
		crontab_time____crontab配置中的五個時間(分 時 日 月 周)參數(shù)對應(yīng)時間取值范圍
		time_struct____ 某個整型時間戳,如:1375027200 對應(yīng)的 分 時 日 月 周
	Return:
	tuple 狀態(tài)碼, 狀態(tài)描述
	"""
	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的指定范圍(crontab_time)中 最接近 指定時間 time_struct 的值"""
	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
	"""
	獲取crontab時間配置參數(shù)取值范圍內(nèi)的所有時間點 的 時間戳
	Args:
		cron_time 符合crontab配置指定的所有時間點
		year_num____指定在哪一年內(nèi) 獲取
		limit_start 開始時間
	Rturn:
		List  所有時間點組成的列表(年月日時分 組成的時間,如2013年7月29日18時56分:201307291856)
	"""
	#按小時 和 分鐘組裝
	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))
	#按天 和 小時組裝
	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))
	#按月 和 天組裝
	month_dhm = []
	#只有30天的月份
	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)):
					#閏年2月份有29天
					if int(day_hm_s[:2]) > 29:
						continue
				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))
	#按年 和 月組裝
	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)
		#開始時間\結(jié)束時間以外的排除
		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:
		#按不在每周指定時間的排除
		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
 
 
#crontab時間參數(shù)各種寫法 的 正則匹配
PATTEN = {
	#純數(shù)字
	'number':'^[0-9]+$',
	#數(shù)字列表,如 1,2,3,6
	'num_list':'^[0-9]+([,][0-9]+)+$',
	#星號 *
	'star':'^\*$',
	#星號/數(shù)字 組合,如 */3
	'star_num':'^\*\/[0-9]+$',
	#區(qū)間 如 8-20
	'range':'^[0-9]+[\-][0-9]+$',
	#區(qū)間/步長 組合 如 8-20/3
	'range_div':'^[0-9]+[\-][0-9]+[\/][0-9]+$'
	#區(qū)間/步長 列表 組合,如 8-20/3,21,22,34
	#'range_div_list':'^([0-9]+[\-][0-9]+[\/][0-9]+)([,][0-9]+)+$'
	}
#各正則對應(yīng)的處理方法
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):
	"""
	判斷是否匹配成功!
	"""
	try:
		tips = tips==None and "文件名稱格式錯誤:job_月-周-天-時-分_文件名.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())
		#解析 時間戳對應(yīng)的 分 時 日 月 周
		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():
	"""測試用實例"""
	#crontab配置中一行時間參數(shù)
	#conf_string = '*/10 * * * * (cd /opt/pythonpm/devpapps; /usr/local/bin/python2.5 data_test.py>>output_error.txt)'
	conf_string = '*/10 * * * *'
	#時間戳
	time_stamp = int(time.time())
 
	#解析crontab時間配置參數(shù) 分 時 日 月 周 各個取值范圍
	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]
 
	#解析 時間戳對應(yīng)的 分 時 日 月 周
	time_struct = get_struct_time(time_stamp)
	print "\nstruct time(minute hour day month week) for %d :" % \
		 time_stamp, time_struct
 
	#將時間戳與crontab配置中一行時間參數(shù)對比,判斷該時間戳是否在配置設(shè)定的時間范圍內(nèi)
	match_res = time_match_crontab(cron_time, time_struct)
	print "\nmatching result:", match_res
 
	#crontab配置設(shè)定范圍中最近接近時指定間戳的一組時間
	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__':
	#請看 使用實例
	strs = 'job_@-@-@-@-@_test02.txt.sh'
	print isdo(strs)
 
	#main()0")

相關(guān)文章

  • Python?cv.Canny()方法參數(shù)與使用方法

    Python?cv.Canny()方法參數(shù)與使用方法

    這篇文章主要介紹了Python?cv.Canny()方法參數(shù)與使用方法,OpenCV提供了cv.Canny()方法,該方法將輸入的原始圖像轉(zhuǎn)換為邊緣圖像,更多相關(guān)內(nèi)容需要的朋友可以參考一下
    2022-07-07
  • Python基礎(chǔ)之模塊相關(guān)知識總結(jié)

    Python基礎(chǔ)之模塊相關(guān)知識總結(jié)

    今天帶大家復習Python基礎(chǔ)知識,文中對模塊相關(guān)知識介紹的非常詳細,對正在學習python基礎(chǔ)的小伙伴們很有幫助,需要的朋友可以參考下
    2021-05-05
  • 運行python提示no module named sklearn的解決方法

    運行python提示no module named sklearn的解決方法

    這篇文章主要介紹了運行python提示no module named sklearn的解決方法,需要的朋友可以參考下
    2020-11-11
  • Python中的jquery PyQuery庫使用小結(jié)

    Python中的jquery PyQuery庫使用小結(jié)

    這篇文章主要介紹了Python中的jquery PyQuery庫使用小結(jié),需要的朋友可以參考下
    2014-05-05
  • python內(nèi)置函數(shù):lambda、map、filter簡單介紹

    python內(nèi)置函數(shù):lambda、map、filter簡單介紹

    Python 內(nèi)置了一些比較特殊且實用的函數(shù),使用這些能使你的代碼簡潔而易讀。下面對python內(nèi)置函數(shù):lambda、map、filter簡單介紹下,需要的朋友參考下吧
    2017-11-11
  • pytorch關(guān)于Tensor的數(shù)據(jù)類型說明

    pytorch關(guān)于Tensor的數(shù)據(jù)類型說明

    這篇文章主要介紹了pytorch關(guān)于Tensor的數(shù)據(jù)類型說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • 基于KL散度、JS散度以及交叉熵的對比

    基于KL散度、JS散度以及交叉熵的對比

    這篇文章主要介紹了基于KL散度、JS散度以及交叉熵的對比,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • 利用python的socket發(fā)送http(s)請求方法示例

    利用python的socket發(fā)送http(s)請求方法示例

    這篇文章主要給大家介紹了關(guān)于利用python的socket發(fā)送http(s)請求的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用python具有一定的參考學習價值,需要的朋友們下面來一起看看吧
    2018-05-05
  • Django高級編程之自定義Field實現(xiàn)多語言

    Django高級編程之自定義Field實現(xiàn)多語言

    這篇文章主要介紹了Django高級編程之自定義Field實現(xiàn)多語言,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-07-07
  • python字符串不可變數(shù)據(jù)類型

    python字符串不可變數(shù)據(jù)類型

    這篇文章主要介紹了python字符串不可變數(shù)據(jù)類型,下文關(guān)于python字符串不可變數(shù)據(jù)類型相關(guān)資料展開的內(nèi)容主要有查找子串及數(shù)量、字符串的替換、分割以及合并、刪除側(cè)邊的空白等內(nèi)容,需要的小伙伴可以參考一下
    2022-02-02

最新評論