如何停止一个程序每天运行多次?

时间:2019-06-22 20:16:55

标签: python datetime

我想防止我的程序在一个日历日内多次运行并接受输入。有办法吗?

我尝试在代码末尾导入日期并将其存储在变量中,然后在代码末尾导入日期并进行比较,但是,当然,当您在代码末尾未定义变量时,第一次运行代码。

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)

使用这种方法,除了第一次没有定义变量last_time之外,它都有效

1 个答案:

答案 0 :(得分:-1)

通过将当前日期附加到文件中,可以比较日历日的差异。

代码:

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)

说明:

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.

文件O / p:

23
24

O / P:

Please wait until tomorrow before entering a new value