python - 使用python从代码中的其他部分开始和停止while循环
问题描述
我正在尝试从我的 python 代码的其他部分开始和停止一个 while 循环,但它运行不正常。
我正在使用 pyTelegramBotAPI 向我的机器人发布一些帖子,但它似乎不起作用:
RunPosts = True
@bot.message_handler(commands=['do','dontdo'])
def KillOrLive(message: telebot.types.Message):
if message.text == '/do':
RunPosts = True
print('OK')
elif message.text == '/dontdo':
RunPosts = False
while RunPosts == True:
for post in posts:
btn = telebot.types.InlineKeyboardMarkup()
view = telebot.types.InlineKeyboardButton("Get Product", url="t.me/{}".format(post.username))
btn.row(view)
if post.kind == 'photo':
bot.send_photo(admins[0],post.file_id,post.caption,reply_markup=btn)
time.sleep(2)
bot.polling(none_stop=True)
解决方案
KillOrLive() 正在创建一个名为 RunPosts 的局部变量,但不会更改全局变量。
只需添加行
global RunPosts
行后:
def KillOrLive(message: telebot.types.Message):
您可能还想更改以下代码
while RunPosts == True:
for post in posts:
btn = telebot.types.InlineKeyboardMarkup()
view = telebot.types.InlineKeyboardButton("Get Product", url="t.me/{}".format(post.username))
btn.row(view)
if post.kind == 'photo':
bot.send_photo(admins[0],post.file_id,post.caption,reply_markup=btn)
time.sleep(2)
至
while RunPosts:
for post in posts:
print("handling post", str(post)[:30])
if not RunPosts:
print("I was told to stop, so this is what I do")
break
btn = telebot.types.InlineKeyboardMarkup()
view = telebot.types.InlineKeyboardButton("Get Product", url="t.me/{}".format(post.username))
btn.row(view)
if post.kind == 'photo':
bot.send_photo(admins[0],post.file_id,post.caption,reply_markup=btn)
time.sleep(2)
如果您想在遇到一篇帖子时立即停止,那会告诉您停止
为了更好地调试,请再添加一张打印:
我建议更换:
bot.polling(none_stop=True)
和
print("Loop has been ended")
bot.polling(none_stop=True)
推荐阅读
- python - 函数内外变量的Python范围
- bigcartel - 在 Bigcartel 中隐藏价格?
- javascript - 如何在 JavaScript 中更改对象键值对的位置
- javascript - 基于出生日期和当前日期的年龄验证
- python - 如何从 *args 创建相对路径?
- arrays - SwiftUI - 将数组保存到 NSSet
- c++ - 为什么我得到 avc1.000000?(FFMPEG、H.264 视频编码、C++)
- r - tidyverse - 根据每行 NA 的数量在嵌套列/列表中进行过滤
- cobol - 我无法弄清楚为什么我的填充空间没有显示在我的 COBOL 应用程序中
- javascript - 尝试从带有条件的 JSON 文件中过滤数组