【问题标题】:Python Global variables not changing when called inside a looped functionPython全局变量在循环函数中调用时不会改变
【发布时间】: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


    【解决方案1】:

    任何将msg_time 引用为global 的函数都需要被告知它应该使用全局版本而不是创建本地版本。在每个函数中,通常在顶部,您应该添加:

    global msg_time
    

    任何将来的使用都将访问/修改全局变量。

    请注意这一行:

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

    不会让msg_time 持续更新,您需要在每次需要时调用它以保持当前时间为最新。

    【讨论】:

    • 仅在写入时。
    • 谢谢,我刚刚检查了添加这个但它没有解决问题,问题是我正在调用全局变量 msg_time 但它使用的是第一次调用的原始时间,它没有更新它与函数中再次调用的实际时间。
    • 我看不到任何代码实际上告诉msg_time 进行更新,它在您的第 3 行设置一次,以后再也不会。 datetime.now 不会持续更新,它只是在调用时设置你的 msg_time 变量一次
    • 非常感谢您的帮助,所以我最好不要全局定义它并将其作为函数并返回结果?另外,当我定义 nz_time 时,我遇到了另一个问题,您现在可以在函数 check_new_feedback 中将其视为全局,然后在 nz_time = next_check_time + datetime.timedelta(hours=13) 之后直接在 new_check_time = datetime.datetime.utcnow() + datetime.timedelta(minutes= 1) 之后,并且在函数中调用它时不会更改 nz_time。有人能解释一下为什么吗?
    • 是的。要么创建一个更新全局msg_time 的函数。然后可以在每次需要更新时调用该函数,但仅在需要显示时才引用全局标志。像这样在 cmets 中检查/响应代码真的很难,如果您还有其他问题,请创建一个新帖子,希望有人可以提供帮助
    猜你喜欢
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    相关资源
    最近更新 更多