gpt4 book ai didi

Python 调度程序未运行导入中调度的函数

转载 作者:太空宇宙 更新时间:2023-11-03 21:01:35 24 4
gpt4 key购买 nike

问题

当这段代码:

# 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.
...

但是:

当上面的 block 被放入一个单独的文件(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

我已经尝试过以下操作:

1. 将 main.py 中的 import someimport 切换为 from someimport import *

正如预期的那样,这并没有改变任何东西。

2. 将第一个 scheduler.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()

这并没有改变任何东西。

3. 在 main.py中导入 schedtime

正如预期的那样,这也没有任何效果。

有没有办法在 someimport.py 中安排 do_something 函数,而无需在 main.py 文件中使用第一个 scheduler.enter 。这就是我试图避免的事情(因为在实际项目中大约有 100 个这样的计划任务,我正在尝试清理主文件)。

以上所有代码均已在 GNU/Linux 下的 python 3.7.3 上进行了测试。

非常感谢!

最佳答案

将单独的模块示例导入 main.py 后,我只需在 scheduler 实例上调用 run() 即可让其正常工作。

# 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 调度程序未运行导入中调度的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55673460/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com