简体   繁体   English

在循环函数中调用时,Python全局变量不变

[英]Python Global variables not changing when called inside a looped function

Program: to get the next check time from a file 'config.txt', if the current time is the same or greater time than the next check time then the program should enter a constant loop, of: 程序:从文件“ config.txt”中获取下一个检查时间,如果当前时间等于或大于下一个检查时间,则程序应进入以下内容的恒定循环:

checking something, doing an action, then recording the next check time to the file, then waiting for the next check time is the same or greater then repeat. 检查某事,执行一个操作,然后将下一个检查时间记录到文件中,然后等待下一个检查时间相同或更长,然后重复。

Problem: The variables outside of the functions are staying the same when being called. 问题:调用时,函数外部的变量保持不变。 See Variable: msg_time which displays the time does not change while in the function 请参见变量:msg_time,该时间在函数中显示时间不变

File named config.txt contains: 名为config.txt的文件包含:

 nextchecktime='2016, 03, 09, 10, 38, 27, 508749' 

time format is %Y, %m, %d, %H, %M, %S, %f in UTC time 时间格式为UTC时间中的%Y,%m,%d,%H,%M,%S,%f

Code: 码:

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()

I'm trying to get the msg_time to display the actual time as at the time of the message. 我正在尝试获取msg_time以显示消息时的实际时间。

Current result: 当前结果:

starting 开始

00:06 10-06-16 : Waiting till 11:07 for next for next check. 00:06 10-06-16:等到11:07进行下一次检查。
00:06 10-06-16 : Checking. 00:06 10-06-16:正在检查
00:06 10-06-16 : Completed check and written time to file, next check time = 11:08 00:06 10-06-16:完成检查并写入文件的时间,下一次检查时间= 11:08
00:06 10-06-16 : Checking. 00:06 10-06-16:正在检查
00:06 10-06-16 : Completed check and written time to file, next check time = 11:09 00:06 10-06-16:完成检查并写入文件的时间,下一次检查时间= 11:09

Result Wanted: 想要的结果:

starting 开始

00:06 10-06-16 : Waiting till 11:07 for next for next check. 00:06 10-06-16:等到11:07进行下一次检查。
00:07 10-06-16 : Checking. 00:07 10-06-16:正在检查。
00:07 10-06-16 : Completed check and written time to file, next check time = 11:08 00:07 10-06-16:完成检查并写入文件的时间,下一次检查时间= 11:08
00:08 10-06-16 : Checking. 00:08 10-06-16:正在检查
00:08 10-06-16 : Completed check and written time to file, next check time = 11:09 00:08 10-06-16:完成检查并写入文件的时间,下一次检查时间= 11:09

Blockquote 块引用

I have a number of other variables I am also trying to change and call on within the function however they are all showing the original value when being called on (I removed them out of the code for simplicity, as solving the msg_time problem should solve all) 我还有很多其他变量也在尝试在函数中调用,但是它们在调用时都显示原始值(为简单起见,我从代码中删除了它们,因为解决msg_time问题应该解决所有问题) )

I think the problem might be to do with not exiting the function, but i'm not sure how else to do it. 我认为问题可能与不退出功能有关,但我不确定还有其他方法。

This is my first program so sorry if its hard to read, any tips will be well appreciated! 这是我的第一个程序,如果很难阅读,对不起,任何提示将不胜感激!

Any function referencing msg_time as a global needs to be told that it should use the global version instead of creating a local one. 必须告知任何将msg_time引用为global函数的函数,该函数应使用全局版本而不是创建本地版本。 In each function, normally at the top, you should add: 在每个函数中,通常应在顶部添加:

global msg_time

Any future uses will then access / modify the global variable. 然后,将来的任何使用都将访问/修改全局变量。

Please note that this line: 请注意这一行:

msg_time = datetime.datetime.now().strftime('%H:%M %d-%M-%y : ')

does not keep msg_time continuously updated, you need to call it every time it's needed to keep your current time up to date. 不会持续更新msg_time ,因此您需要在每次需要时调用它以保持当前时间为最新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM