python - Telebot 看到新消息时如何退出脚本
问题描述
我有两个使用批处理脚本运行的 python 脚本。一旦执行了一个脚本,下一个脚本就会启动。我需要其中一个脚本,即 Telebot 脚本,在 .json 文件中记录消息后退出。不幸的是,虽然消息确实被记录下来,但我在退出脚本时遇到了麻烦,这意味着我的第二个 python 文件没有被执行。
import telebot
import json
import os
import sys
import time
with open('JSON_file.json') as f:
data = json.load(f)
group_chat_id = 'CHAT_ID_HERE'
hbot = telebot.TeleBot('BOT_TOKEN_HERE')
hbot.send_photo(chat_id = group_chat_id, caption = data, photo = open('C:/Users/.../image.jpg', 'rb'))
temp = ""
@hbot.message_handler(func=lambda message: True)
def get_input(message):
global temp
message_str = str(message.text)
message_str = message_str.strip()
temp = message_str
print(temp)
with open('JSON_file.json', 'w') as json_file:
json.dump(temp, json_file)
hbot.stop_polling()
if temp != "":
quit()
return
if __name__ == "__main__":
hbot.polling()
我使用可执行的 .bat 文件运行代码,但是,一旦收到消息,下面的代码就不会退出。有谁知道为什么 quit() 命令不会停止我的代码?
提前致谢)
解决方案
我建议使用 sys.exit 而不是退出:https ://docs.python.org/3/library/sys.html#sys.exit
在 python 中,我们有一个内置的 quit() 函数,用于退出 python 程序。当它遇到系统中的quit()函数时,它会完全终止程序的执行。
它不应该在生产代码中使用,并且这个函数应该只在解释器中使用。
推荐阅读
- asp.net-core-2.1 - 找不到 AddCommandLine .netcore 2.1
- windows - 如何从 Powershell 最大化 Skype
- python - 减少方向码
- c - Fisher 数的结果检查不正确
- fonts - 字体在页面的某些部分正确显示,但在其他部分不正确
- git - 带有本地更改的 Git-svn rebase
- javascript - 反应表集合上的日期自定义过滤器
- java - 发布 Power Manager onPause 的原因是什么?
- verilog - Verilog - 故障定时信号到模块
- javascript - 如何获取div的innerHTML,其中包含一个div?