python-3.x - Python while True 阻止以前的代码执行
问题描述
我正在使用 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 位
解决方案
解决方案是sys.stdout.flush()
在各种print()
恢复功能之后添加print()
,而为了使代码再次工作,我不得不更改 Telepot 功能
MessageLoop(bot, messageHandler.handle).run_as_thread()
这不能正常工作:
bot.message_loop(messageHandler.handle)
推荐阅读
- java - 在使用 Spring Security 的 httpBasic auth 的 POST 方法中出现 HTTP 403 错误
- c - 为 Windows 编译二进制文件的问题
- postgresql - 如何数据库查询然后检查结果
- c# - Post 服务调用了一次,但在 .NET Core Web API 上被调用了两次
- eclipse - Eclipse 中的 Smart Caret 对某些文件停止工作
- python - 在 Python 中打开一个可执行文件不断写入的文件时出错
- docker - 如何从 docker weblogic 访问远程 JMS 队列
- apache-kafka - 从 Kafka 中删除 __Consumer_offset 主题
- node.js - Heroku 在 60 秒内无法绑定 PORT
- powershell - 使用 Powershell 检索远程文件共享“共享权限”