Skip to main content
 首页 » 编程设计

python之在 Python 中 sleep 时保持活跃

2025年05月04日10lvdongjie

if ":!giveaway" in prevdata and senderusr in securelist and agive == 0: 
    agive = agive+1 
    message("Giveaway started by: " + senderusr) 
    time.sleep(3) 
    agive = 0 
    enteredgiveaway = enteredgiveaway.rstrip() 
    enteredgiveaway = enteredgiveaway.split(" ") 
    gg = random.choice(enteredgiveaway) 
    message("The winner of the giveaway is: " + gg) 
    gg = "" 
    enteredgiveaway = "" 
 
if "PRIVMSG" in prevdata and agive == 1: 
    enteredgiveaway += senderusr + " " 

第一个 if 开始赠品,然后在 3 秒后将选择一个在 IRC 中键入的随机用户并向 IRC 发送消息说谁赢了。

但是,我的问题是第二个 if 无法收集用户,因为第一个命令使程序休眠而另一个 if 无法工作。

我如何在 sleep 的同时让程序能够处理其他事情?

(IRC 机器人)

完整代码:http://pastebin.com/Qr8hAH14

请您参考如下方法:

让第一个 if 子句设置一个 Timer ,调用一个方法来执行您现在在 sleep 后执行的操作。

from threading import Timer 
 
def giveaway(): 
    agive = 0 
    enteredgiveaway = enteredgiveaway.rstrip() 
    enteredgiveaway = enteredgiveaway.split(" ") 
    gg = random.choice(enteredgiveaway) 
    message("The winner of the giveaway is: " + gg) 
    gg = "" 
    enteredgiveaway = "" 

在您引用的代码段中:

if ":!giveaway" in prevdata and senderusr in securelist and agive == 0: 
    agive = agive+1 
    message("Giveaway started by: " + senderusr) 
    t = Timer(3, giveaway) 
    t.start() 
 
... 

这有点粗略,因为我无法分辨例如 enteredgiveaway 在您的代码示例中的来源。因此,根据您的其余代码,您可能需要稍微重新组织/重组才能使其正常工作。如果您还没有这样做,那么将所有内容都放在一个类中并使用实例变量可能会更好。