백엔드 개발 파이썬 튜토리얼 python实现的解析crontab配置文件代码

python实现的解析crontab配置文件代码

Jun 16, 2016 am 08:43 AM
python

#/usr/bin/env python
#-*- coding:utf-8 -*-
 
"""
1.解析 crontab 配置文件中的五个数间参数(分 时 日 月 周),获取他们对应的取值范围
2.将时间戳与crontab配置中一行时间参数对比,判断该时间戳是否在配置设定的时间范围内
"""
 
#$Id $
 
import re, time, sys
from Core.FDateTime.FDateTime import FDateTime
 
def get_struct_time(time_stamp_int):
	"""
	按整型时间戳获取格式化时间 分 时 日 月 周
	Args:
		time_stamp_int 为传入的值为时间戳(整形),如:1332888820
		经过localtime转换后变成
		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____ 匹配内容
	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()):
	"""处理纯数字"""
	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()):
	"""处理数字列表 如 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()):
	"""星号/数字 组合 如 */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()):
	"""处理区间 如 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()):
	"""处理区间/步长 组合 如 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 五个时间参数中的任意一个"""
	#去除空格,再拆分
	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):
			#记录拆分后的纯数字参数
			number_conf.append(conf_val)
		else:
			#记录拆分后纯数字以外的参数,如通配符 * , 区间 0-8, 及 0-8/3 之类
			other_conf.append(conf_val)
	if other_conf:
		#处理纯数字外各种参数
		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:
			#纯数字多于1,或纯数字与其它参数共存,则数字作为时间列表
			res = handle_nlist(val=','.join(number_conf), ranges=ranges, res=res)
		else:
			#只有一个纯数字存在,则数字为时间 间隔
			res = handle_num(val=number_conf[0], ranges=ranges, res=res)
	return res
 
def parse_crontab_time(conf_string):
	"""
	解析crontab时间配置参数
	Args:
		conf_string  配置内容(共五个值:分 时 日 月 周)
					 取值范围 分钟:0-59 小时:1-23 日期:1-31 月份:1-12 星期:0-6(0表示周日)
	Return:
	crontab_range	 list格式,分 时 日 月 周 五个传入参数分别对应的取值范围
	"""
	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配置中一行时间参数对比,判断该时间戳是否在配置设定的时间范围内
	Args:
		crontab_time____crontab配置中的五个时间(分 时 日 月 周)参数对应时间取值范围
		time_struct____ 某个整型时间戳,如:1375027200 对应的 分 时 日 月 周
	Return:
	tuple 状态码, 状态描述
	"""
	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时间配置参数取值范围内的所有时间点 的 时间戳
	Args:
		cron_time 符合crontab配置指定的所有时间点
		year_num____指定在哪一年内 获取
		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)
		#开始时间\结束时间以外的排除
		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时间参数各种写法 的 正则匹配
PATTEN = {
	#纯数字
	'number':'^[0-9]+$',
	#数字列表,如 1,2,3,6
	'num_list':'^[0-9]+([,][0-9]+)+$',
	#星号 *
	'star':'^\*$',
	#星号/数字 组合,如 */3
	'star_num':'^\*\/[0-9]+$',
	#区间 如 8-20
	'range':'^[0-9]+[\-][0-9]+$',
	#区间/步长 组合 如 8-20/3
	'range_div':'^[0-9]+[\-][0-9]+[\/][0-9]+$'
	#区间/步长 列表 组合,如 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':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())
		#解析 时间戳对应的 分 时 日 月 周
		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配置中一行时间参数
	#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时间配置参数 分 时 日 月 周 各个取值范围
	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]
 
	#解析 时间戳对应的 分 时 日 月 周
	time_struct = get_struct_time(time_stamp)
	print "\nstruct time(minute hour day month week) for %d :" % \
		 time_stamp, time_struct
 
	#将时间戳与crontab配置中一行时间参数对比,判断该时间戳是否在配置设定的时间范围内
	match_res = time_match_crontab(cron_time, time_struct)
	print "\nmatching result:", match_res
 
	#crontab配置设定范围中最近接近时指定间戳的一组时间
	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")
로그인 후 복사

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

PHP와 Python : 다른 패러다임이 설명되었습니다 PHP와 Python : 다른 패러다임이 설명되었습니다 Apr 18, 2025 am 12:26 AM

PHP는 주로 절차 적 프로그래밍이지만 객체 지향 프로그래밍 (OOP)도 지원합니다. Python은 OOP, 기능 및 절차 프로그래밍을 포함한 다양한 패러다임을 지원합니다. PHP는 웹 개발에 적합하며 Python은 데이터 분석 및 기계 학습과 같은 다양한 응용 프로그램에 적합합니다.

PHP와 Python 중에서 선택 : 가이드 PHP와 Python 중에서 선택 : 가이드 Apr 18, 2025 am 12:24 AM

PHP는 웹 개발 및 빠른 프로토 타이핑에 적합하며 Python은 데이터 과학 및 기계 학습에 적합합니다. 1.PHP는 간단한 구문과 함께 동적 웹 개발에 사용되며 빠른 개발에 적합합니다. 2. Python은 간결한 구문을 가지고 있으며 여러 분야에 적합하며 강력한 라이브러리 생태계가 있습니다.

PHP와 Python : 그들의 역사에 깊은 다이빙 PHP와 Python : 그들의 역사에 깊은 다이빙 Apr 18, 2025 am 12:25 AM

PHP는 1994 년에 시작되었으며 Rasmuslerdorf에 의해 개발되었습니다. 원래 웹 사이트 방문자를 추적하는 데 사용되었으며 점차 서버 측 스크립팅 언어로 진화했으며 웹 개발에 널리 사용되었습니다. Python은 1980 년대 후반 Guidovan Rossum에 의해 개발되었으며 1991 년에 처음 출시되었습니다. 코드 가독성과 단순성을 강조하며 과학 컴퓨팅, 데이터 분석 및 기타 분야에 적합합니다.

Python vs. JavaScript : 학습 곡선 및 사용 편의성 Python vs. JavaScript : 학습 곡선 및 사용 편의성 Apr 16, 2025 am 12:12 AM

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

숭고한 코드 파이썬을 실행하는 방법 숭고한 코드 파이썬을 실행하는 방법 Apr 16, 2025 am 08:48 AM

Sublime 텍스트로 Python 코드를 실행하려면 먼저 Python 플러그인을 설치 한 다음 .py 파일을 작성하고 코드를 작성한 다음 CTRL B를 눌러 코드를 실행하면 콘솔에 출력이 표시됩니다.

vscode에서 코드를 작성하는 위치 vscode에서 코드를 작성하는 위치 Apr 15, 2025 pm 09:54 PM

Visual Studio Code (VSCODE)에서 코드를 작성하는 것은 간단하고 사용하기 쉽습니다. vscode를 설치하고, 프로젝트를 만들고, 언어를 선택하고, 파일을 만들고, 코드를 작성하고, 저장하고 실행합니다. VSCODE의 장점에는 크로스 플랫폼, 무료 및 오픈 소스, 강력한 기능, 풍부한 확장 및 경량 및 빠른가 포함됩니다.

Python에서 비주얼 스튜디오 코드를 사용할 수 있습니다 Python에서 비주얼 스튜디오 코드를 사용할 수 있습니다 Apr 15, 2025 pm 08:18 PM

VS 코드는 파이썬을 작성하는 데 사용될 수 있으며 파이썬 애플리케이션을 개발하기에 이상적인 도구가되는 많은 기능을 제공합니다. 사용자는 다음을 수행 할 수 있습니다. Python 확장 기능을 설치하여 코드 완료, 구문 강조 및 디버깅과 같은 기능을 얻습니다. 디버거를 사용하여 코드를 단계별로 추적하고 오류를 찾아 수정하십시오. 버전 제어를 위해 git을 통합합니다. 코드 서식 도구를 사용하여 코드 일관성을 유지하십시오. 라인 도구를 사용하여 잠재적 인 문제를 미리 발견하십시오.

메모장으로 파이썬을 실행하는 방법 메모장으로 파이썬을 실행하는 방법 Apr 16, 2025 pm 07:33 PM

메모장에서 Python 코드를 실행하려면 Python 실행 파일 및 NPPEXEC 플러그인을 설치해야합니다. Python을 설치하고 경로를 추가 한 후 nppexec 플러그인의 명령 "Python"및 매개 변수 "{current_directory} {file_name}"을 구성하여 Notepad의 단축키 "F6"을 통해 Python 코드를 실행하십시오.

See all articles