如何在Python中使用调度获得随机选择

2024-06-26 14:54:12 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我想弄明白为什么choice不能和调度器一起工作。目前,它并没有每次都选择一个新的说法。调度程序运行良好,我在其他上下文中成功地使用了这个选项。你知道吗

我做错什么了?如果信息有用的话,我也会通过解释器说“import[project name]”来运行它。你知道吗

谢谢!你知道吗

from apscheduler.scheduler import Scheduler
from random import choice

#change this to a text file
cat_sayings = [
"I can haz?",
"I pooped in your shoe.",
"I ate the fish.",
"I want out.",
"Food? What...? Food?",
"When are you coming home? There's food that needs eating!",
"Lulz, I am sleeping in your laundry.",
"I didn't do it. Nope."]

sayings = choice(cat_sayings)

def cat_job(sayings):

    print sayings


s = Scheduler()
s.add_cron_job(cat_job, args=[sayings], second='*/30')
s.start()

Tags: infromimport程序运行信息yourfood选项
1条回答
网友
1楼 · 发布于 2024-06-26 14:54:12

您只在模块的顶层调用choice(cat_sayings)一次,以后不再调用。所以,它会选择一个随机的选择,而不会选择一个新的。你知道吗

要解决此问题,只需将代码移到函数中:

def cat_job(sayings):
    print choice(sayings)

# ...

s.add_cron_job(cat_job, args=[cat_sayings], second='*/30')

相关问题 更多 >