【问题标题】:Python while True preventing previous code executionPython while True 阻止以前的代码执行
【发布时间】:2018-10-24 03:03:58
【问题描述】:

我正在使用 Telepot(python) 构建一个电报机器人,但发生了一件奇怪的事情:

因为机器人应该继续运行,所以我设置了一个

while 1:
    time.sleep(.3)

在我的机器人结束时,就在我定义如何处理 MessageLoop 之后。

机器人有一些print() 来断言机器人正在设置(或者更好的是,它正在设置消息处理程序)并且它正在阅读聊天,等待任何输入。

问题是,如果我在没有

的情况下运行代码
while 1:
    time.sleep(.3)

它打印消息并停止执行(没有循环等待新输入),但如果我添加 while 1: (...) 代码在能够打印任何内容之前停止。

代码如下:

"""Launch the bot."""
import json
import telepot
from telepot.loop import MessageLoop
import time
from base import splitter
from base import handler

messageHandler = handler.Handler()

with open('triggers.json') as f:
    triggers = json.load(f)
with open('config.json') as f:
    config = json.load(f)

botKey = config['BOT_KEY']

# define the bot and the botname
bot = telepot.Bot(botKey)
botName = bot.getMe()['username']

# split commands in arrays ordered by priority
configSplitter = splitter.Splitter()
triggers = configSplitter.splitByPriority(triggers)

# define the handler
messageHandler.setBotname(botName)
messageHandler.setMessages(triggers)

# handle the messageLoop
print("setting up the bot...")
MessageLoop(bot, messageHandler.handle).run_as_thread()
print("Multibot is listening!")

# loop to catch all the messages
while 1:
    time.sleep(.3)

Python 版本:3.6 32 位

【问题讨论】:

    标签: python-3.x telegram thread-sleep telepot


    【解决方案1】:

    解决方案是在各种print()之后添加sys.stdout.flush()以恢复print()的功能,而为了使代码再次工作我不得不更改telepot功能

    MessageLoop(bot, messageHandler.handle).run_as_thread()
    

    无法正常工作:

    bot.message_loop(messageHandler.handle)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      • 2016-11-05
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      相关资源
      最近更新 更多