奇怪的一个(检查上次执行python文件的时间)



奇怪的一个。我有一个应用程序描述,每当笔记本电脑从睡眠中醒来时,它都会调用一个python文件。apple脚本打开终端并调用python文件。python文件中有一些函数,如果是一天中的某个时间,这些函数会运行某些代码。像这样:

now = datetime.datetime.now().hour
if 9 <= now <= 10 :
then do python stuff...
now = datetime.datetime.now().hour
if 15<= now <= 18 :
then do python stuff...
now = datetime.datetime.now().hour
if 22<= now <= 23 :
then do python stuff...

因此,正如您在上面看到的,一天中的某些时间会执行特定的python函数。我的问题是,我只想在这个时间段内运行一次python函数。目前,如果笔记本电脑在上述时间内唤醒两次,那么python函数将运行两次。有没有办法在我调用的python文件中解决这个问题?我知道可能有很多方法可以解决这个问题,即应用程序描述、终端命令或python文件。老实说,我不知道从哪里开始,所以我猜我从python开始,然后向后工作。

我在想,我们是否可以检查python文件最后一次执行的时间,如果它已经在指定的时间范围内被驱逐,则停止它。那么这可能是一种阻止它运行两次的方法吗?

将上次执行的时间保存到文件中:

...
with open('path/to/file', 'w') as f:
f.write(str(now.timestamp()))

在脚本的顶部,尝试从所述文件中读取:

try:
with open('path/to/file') as f:
last_execution_time = datetime.fromtimestamp(float(f.read()))
except FileNotFoundError:  # will happen in the first execution, obviously
last_execution_time = now
# do whatever logic you want to perform with `last_execution_time` and `now`
...

最新更新