Python while True 阻止之前的代码执行

Python while True preventing previous code execution

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

因为机器人应该保持 运行ning,所以我设置了

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 位

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

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

无法正常工作的:

bot.message_loop(messageHandler.handle)