[英]How do I stop a program from running more than once a day?
I want to prevent my program from running and accepting input more than once a calendar day. 我想防止我的程序在一个日历日内多次运行并接受输入。 Is there a way to do this? 有没有办法做到这一点?
I tried importing the date at the end of my code and storing it in variable and then importing the date at the start of the code and comparing them but of course, the variable at the end of the code is not defined when you run the code for the first time. 我尝试在代码末尾导入日期并将其存储在变量中,然后在代码开始处导入日期并进行比较,但是,当然,在运行代码时未定义代码末尾的变量首次。
import datetime
new_time = str(datetime.datetime.now())
new_time = new_time[8:10]
new_time = int(new_time)
while new_time == last_time:
print("Please wait until tomorrow before entering a new value")
last_time = str(datetime.datetime.now())
last_time = last_time[8:10]
last_time = int(last_time)
With this approach, it works except for the first time when the variable last_time is not defined 使用这种方法,除了第一次没有定义变量last_time以外,它都有效
By appending the current date into a file, you can compare the calendar day difference. 通过将当前日期附加到文件中,可以比较日历日差。
Code: 码:
import datetime
new_day = int(datetime.datetime.now().strftime("%d"))
last_day = 0
with open("last_time.txt", "r") as f:
lines = f.read().splitlines()
last_day = lines[-1]
if new_day == int(last_day):
print("Please wait until tomorrow before entering a new value")
with open("last_day.txt", "a+") as f:
last_day = datetime.datetime.now().strftime("%d")
f.write(last_day)
Explanation: 说明:
1. Create a text file(last_time.txt) and give the default day as when you are running the script for first time(as today(24))
2. get the new_day as day from datetime.now() and convert into an integer.
3. By default keeping the last_day=0 or you can give the current date for first time
4. Reading the last time from the last line of the file
5. If new_day and last_day are equal, then print the message to the user.
6. Fetch the current day as last_day and write to a file in append mode.
File O/p: 文件O / p:
23
24
O/P: O / P:
Please wait until tomorrow before entering a new value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.