Python调度程序没有运行在imp中调度的函数

2024-09-30 12:21:38 发布

您现在位置: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()

在被调用的文件中(主.py)它按预期运行(dou something函数每秒运行一次),产生以下输出:

^{pr2}$

但是:

当上述块放入单独的文件(someimport.pysomeimport.py中导入主.py不再执行do\u 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

我已经试过以下方法:

1在主.py

正如人们所预料的那样,这并没有改变任何东西。在

2放第一个调度程序.enter调用单独的函数(run),该函数在导入后调用:
# 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()

这并没有改变什么。在

三。在主.py还有。

正如所料,这也没有任何效果。在

有什么方法可以安排中的do\u something函数吗someimport.py,没有第一个调度程序.enter在主.py文件。 这是我试图避免的事情(因为在真实的项目中,有大约100个这样的计划任务,我正试图清理主文件)。在

以上所有代码都在GNU/Linux下的python3.7.3上进行了测试。在

先谢谢你!在


Tags: runpyimporttimemainnotdosomething
1条回答
网友
1楼 · 发布于 2024-09-30 12:21:38

我只能通过在导入scheduler实例后调用run()来让您的独立模块示例正常工作主.py. 在

# main.py - this file get's run directly
import someimport

someimport.scheduler.run()  # Blocks until all events finished

产生:

^{pr2}$

根据the docs,必须调用scheduler.run()才能运行任何计划的任务。它自己的scheduler.enter()方法将只调度事件,而不是运行它们。在

相关问题 更多 >

    热门问题