代码之家  ›  专栏  ›  技术社区  ›  Tails128

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

  •  1
  • Tails128  · 技术社区  · 6 年前

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

    由于机器人应该继续运行,我设置了

    while 1:
        time.sleep(.3)
    

    在我的机器人程序的末尾,就在我定义了如何处理MessageLoop之后。

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

    问题是如果我在没有

    而1:
    时间睡眠(.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位

    1 回复  |  直到 6 年前
        1
  •  0
  •   Tails128    6 年前

    解决方案是添加 sys.stdout.flush() 在各种 print() 恢复的功能 打印() ,而为了使代码再次工作,我必须更改telepot函数

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

    无法正常工作:

    bot.message_loop(messageHandler.handle)