【发布时间】:2021-10-19 18:15:02
【问题描述】:
我有一个名为 number.txt 的文本文件。 number.txt 的内容是单个字符串"10",然后被读入一个名为“data”的变量中。然后创建一个新变量"var_to_eval",并将data 作为其值分配给它。
我还有一个函数 "f1" 应该接收 var_to_eval 作为其默认参数。
该函数的作用是将number.txt中包含的值加10,然后将新值保存到number.txt中。
我正在使用计划库 [https://github.com/dbader/schedule][1] 在无限循环中仅重新运行函数 f1 以读取文件,然后在内容中添加 10再次保存文件。
但是因为var_to_eval只在代码运行时计算一次,所以当schedule运行函数时,从var_to_eval作为函数参数传入的值不是更新值而是初始值。
import schedule
import time
with open ("number.txt", "r") as myfile:
data = int(myfile.read())
var_to_eval = data
def f1(arg1 = var_to_eval):
global var_to_eval
print(arg1)
arg1 += 10
with open("number.txt", "w") as myfile:
myfile.write(str(arg1))
var_to_eval = arg1
schedule.every(3).seconds.do(f1)
while True:
schedule.run_pending()
time.sleep(1)
输出:
20
20
20
我可以包括
with open ("number.txt", "r") as myfile:
data = int(myfile.read())
var_to_eval = data
在解决问题的函数中,但是,我想找到一个解决方案,无论“计划”重新运行该函数多少次,从硬盘驱动器执行的读取操作都不会超过一次并从内存中读取更新后的数据。
当编码正确时,代码的输出将是:
20
30
40
.
.
.
所以我想重申,可接受的解决方案只能包含一个从硬盘驱动器的初始读取操作。
如果需要进一步澄清以回答问题,请提出,我会尽力进一步描述问题。
(有关如何使用时间表的参考,请参阅下面的代码片段):
进口时间表 进口时间
定义工作(): print("我正在工作...")
schedule.every(3).seconds.do(job)
当真时: schedule.run_pending() time.sleep(1)
【问题讨论】:
-
因为你从来没有真正用参数调用
f1(),arg1总是有它的默认值——在定义函数时被评估一次。我完全不明白您为什么要尝试使用参数,只需使用全局变量即可。 -
是的,它的工作方式与您的建议一样。
import schedule import time with open ("number.txt", "r") as myfile: data = int(myfile.read()) var_to_eval = data def f1(): global var_to_eval print(var_to_eval) var_to_eval += 10 with open("number.txt", "w") as myfile: myfile.write(str(var_to_eval)) schedule.every(3).seconds.do(f1) while True: schedule.run_pending() time.sleep(1)这是你的意思吗? -
您能否将您的回复添加为答案,以便我接受?