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

如何在Python中使用调度获得随机选择,python,scheduled-tasks,scheduler,Python,Scheduled Tasks,Scheduler,所以我想弄明白为什么choice不能和调度器一起工作。目前,它并没有每次都选择一个新的说法。调度程序运行良好,我在其他上下文中成功地使用了该选项 那么我做错了什么?如果这些信息有用,我也会通过解释器说“import[project name]”来实现这一点 谢谢 from apscheduler.scheduler import Scheduler from random import choice #change this to a text file cat_sayings = [ "I

所以我想弄明白为什么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()

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

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

def cat_job(sayings):
    print choice(sayings)

# ...

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

因为你只需要选择一句话,然后在每一个函数中重复使用它。让函数每次选择一个新的短语来代替。。。