Как остановить запуск программы более одного раза в день? - PullRequest
0 голосов
/ 22 июня 2019

Я хочу запретить моей программе запускаться и принимать ввод более одного раза в календарный день. Есть ли способ сделать это?

Я попытался импортировать дату в конце моего кода и сохранить ее в переменной, а затем импортировать дату в начале кода и сравнить их, но, конечно, переменная в конце кода не определяется, когда вы запустите код в первый раз.

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 голосов
/ 24 июня 2019

Добавляя текущую дату в файл, вы можете сравнить разницу календарного дня.

Код:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...