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

Weird one (checking last time a python file was executed)

奇怪的一个。我有一个 applescript,每次笔记本电脑从睡眠中唤醒时都会调用 python 文件。苹果脚本打开终端并调用 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 文件中解决这个问题? 我知道可能有很多方法可以解决这个问题,即 applescripts、终端命令或 python 文件。老实说,我不知道从哪里开始,所以我猜 id 从 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`
...