Python调度程序未运行导入中安排的函数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python调度程序未运行导入中安排的函数相关的知识,希望对你有一定的参考价值。
问题
当这段代码:
# main.py - this file gets run directly.
import sched
import time
scheduler = sched.scheduler(time.time, time.sleep)
print("before definition")
def do_something():
print("do_something is being executed.")
scheduler.enter(1, 5, do_something)
print("post definition")
scheduler.enter(1, 5, do_something)
# Do something, so that the program does not terminate.
do_not_terminate()
在被调用的文件(main.py)中,它按预期运行(每秒运行do_something函数。),产生以下输出:
before definition
post definition
do_something is being executed.
do_something is being executed.
do_something is being executed.
do_something is being executed.
do_something is being executed.
do_something is being executed.
...
But:
当上面的块被放入一个单独的文件(someimport.py)并且someimport.py被导入main.py时,do_something函数不再被执行。 [代码如下所示:]
# someimport.py - this file gets imported in main.py
import sched
import time
scheduler = sched.scheduler(time.time, time.sleep)
print("before definition")
def do_something():
print("do_something is being executed.")
scheduler.enter(1, 5, do_something)
print("post definition")
scheduler.enter(1, 5, do_something)
# main.py - this file get's run directly
import someimport
# Do something, so that the program does not terminate.
do_not_terminate()
仅生成以下输出(当然不会显示错误消息):
before definition
post definition
I already tried the following:
1. Switchimport someimport
to from someimport import *
in main.py
正如预期的那样,这并没有改变任何东西。
2. Put the first scheduler.enter call into a separate function(run), which is called after the import:# someimport.py - this file gets imported in main.py
import sched
import time
scheduler = sched.scheduler(time.time, time.sleep)
print("before definition")
def do_something():
print("do_something is being executed.")
scheduler.enter(1, 5, do_something)
print("post definition")
def run():
scheduler.enter(1, 5, do_something)
# main.py - this file get's run directly
import someimport
someimport.run()
# Do something, so that the program does not terminate.
do_not_terminate()
这并没有改变任何事情。
3. importing sched and time in main.py aswell.正如所料,这也没有任何影响。
有没有办法在someimport.py中安排do_something函数,而没有main.py文件中的第一个scheduler.enter。这是我试图避免的事情(因为在真正的项目中有大约100个这样的计划任务,我正在尝试清理主文件)。
上面的所有代码都在GNU / Linux下的python 3.7.3上进行了测试。
提前谢谢了!
答案
我只能通过在run()
实例上将scheduler
导入main.py后才能使你的单独模块示例工作。
# main.py - this file get's run directly
import someimport
someimport.scheduler.run() # Blocks until all events finished
生产:
before definition
post definition
do_something is being executed.
do_something is being executed.
根据the docs,必须调用scheduler.run()
才能执行任何计划任务。它本身的scheduler.enter()
方法只是安排事件,而不是运行它们。
以上是关于Python调度程序未运行导入中安排的函数的主要内容,如果未能解决你的问题,请参考以下文章
ubuntu中安装好了mininet 但是运行python代码时,报错?
没有在Google App Engine中安排的Cron作业