简体   繁体   English

条件为真时如何自动运行脚本?

[英]How to auto-run a script when a condition is true?

Let's say I have the following python program: 假设我有以下python程序:

def Is_it_Midnight(args):
    print("It's midnight!")

and I want the .py script to execute itself when a certain condition is true, say "when the clock strikes midnight". 我希望.py脚本能够在某个特定条件为真时自行执行,例如说“当时钟敲响午夜时分”。

Is that possible? 那可能吗?

You can use the threading library to have the routine restart itself periodically. 您可以使用线程库使例程定期重新启动。 In this specific case, every 86400 seconds (1 day). 在这种情况下,每86400秒(1天)。

modify your code to: 修改您的代码以:

import threading
import time

def Is_it_Midnight(args):
    threading.Timer(86400, Is_it_Midnight).start()
    print("It's midnight!")

Then you just have to get the code to run at midnight the first time. 然后,您只需要让代码第一次在午夜运行即可。 Something like: 就像是:

seconds = time.time()
since_midnight = seconds % 86400
time.sleep(86400-since_midnight)
Is_it_Midnight()

I'm not sure how you'd handle passing args into the routine. 我不确定如何处理将args传递到例程中。

There are a few options to run a script. 有一些选项可以运行脚本。

My favorite is to create myscript.py and within it define a function, let's say def alarm()... and then in your main script: 我最喜欢的是创建myscript.py并在其中定义一个函数,例如def alarm()...然后在您的主脚本中:

import myscript

And when the time comes, call: 时间到了,请致电:

myscript.alar()

There is another way, you can call execfile("myscript.py") 还有另一种方法,您可以调用execfile("myscript.py")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM