【发布时间】:2016-03-09 11:00:30
【问题描述】:
程序:从文件'config.txt'中获取下一次检查时间,如果当前时间与下一次检查时间相同或更大,则程序应进入一个恒定循环,为:
检查某事,做一个动作,然后将下一次检查时间记录到文件中,然后等待下一次检查时间相同或更大,然后重复。
问题: 函数之外的变量在被调用时保持不变。请参阅变量:msg_time,它显示的时间在函数中不会改变
名为 config.txt 的文件包含:
nextchecktime='2016, 03, 09, 10, 38, 27, 508749'时间格式为 UTC 时间的 %Y、%m、%d、%H、%M、%S、%f
代码:
import datetime, time, re
msg_time = datetime.datetime.now().strftime('%H:%M %d-%M-%y : ') # Date format prefix at the start of each message to user.
#Get last time program run from config file
config_file = open('config.txt', 'r+')
config_data = config_file.read()
config_file.close()
next_check_time_regex = re.compile(r'nextchecktime\=\'((.)*)\'') # Find nextchecktime= line in config file
mo = next_check_time_regex.search(config_data)
next_check_time = datetime.datetime.strptime(mo.group(1), '%Y, %m, %d, %H, %M, %S, %f') #phrasing date plain text from config file to next_check_time as a datetime format (UTC time - same time as sever time)
nz_time = next_check_time + datetime.timedelta(hours=13) #converting from UTC time to GMT + 13 (same time as myself)
def time_break(): #breaks until new_check_time == time now
while datetime.datetime.utcnow() <= new_check_time:
time.sleep(1)
# Search for new feedbacks
def check_new_feedback():
global new_check_time
print(msg_time + 'Checking.')
new_check_time = datetime.datetime.utcnow() + datetime.timedelta(minutes= 1) #update new_check_time to next time to check
### Checking feedback code in here (removed) ###
config_file = open('config.txt', 'r+')
config_data = config_file.read()
mo = next_check_time_regex.sub(r"nextchecktime='" + str(new_check_time.strftime('%Y, %m, %d, %H, %M, %S, %f')) + "'", config_data)
config_file.seek(0) # Back to line 0 in file
config_file.write(mo) # writing new_check_time to file so when program closes can remember last check time.
print(msg_time + 'Completed check and written time to file, next check time = ', new_check_time.strftime('%H:%M'))
config_file.close() # close config file
time_break()
check_new_feedback()
#Starting program here to get into a loop
print('starting \n')
if datetime.datetime.utcnow() <= next_check_time:
print(msg_time + 'Waiting till %s for next for next check.' % next_check_time.strftime('%H:%M'))
while datetime.datetime.utcnow() <= next_check_time:
time.sleep(1)
check_new_feedback()
else:
check_new_feedback()
我正在尝试让 msg_time 显示消息发出时的实际时间。
当前结果:
开始
00:06 10-06-16 : 等到 11:07 进行下一次检查。
00:06 10-06-16:检查。
00:06 10-06-16 : 完成检查和书面时间 到文件,下次检查时间 = 11:08
00:06 10-06-16 : Checking.
00:06 10-06-16 : 完成检查并写入文件时间,下次检查时间 = 11:09
想要的结果:
开始
00:06 10-06-16 : 等到 11:07 下一个 下次检查。
00:07 10-06-16:检查。
00:07 10-06-16 : 完成检查并写入归档时间,下次检查时间 = 11:08
00:08 10-06-16:检查。
00:08 10-06-16 : 完成检查 并写入归档时间,下次检查时间 = 11:09块引用
我还有许多其他变量,我也试图在函数中更改和调用,但是它们在被调用时都显示原始值(为简单起见,我将它们从代码中删除,以解决 msg_time 问题应该解决所有)
我认为问题可能与不退出该功能有关,但我不确定该怎么做。
这是我的第一个程序,如果难以阅读,非常抱歉,任何提示将不胜感激!
【问题讨论】:
标签: python function loops python-3.x global-variables