python - 等待python中的值更改
问题描述
我正在 ping 一个带有不和谐机器人设置的服务器的 IP。我希望它在 ping 的输出从 1 变为 0 时发送一条消息,这意味着服务器已离线,但在我当前的设置中,它只是一个 while 循环,它会一遍又一遍地发送消息,但我只希望它每当状态从1变为0时发送 1 条消息
@tasks.loop()
async def serverstatus():
channel=bot.get_channel(850531139403776040)
status=os.system("ping -c 1 "+ip)
messagesent=0
if status==0:
await channel.send(f"<@&850539902675845170> Server Offline")
else:
await channel.send("Server Online")
解决方案
was_online = True
@tasks.loop()
async def serverstatus():
global was_online
channel = bot.get_channel(850531139403776040)
is_online = os.system("ping -c 1 "+ip)
if was_online and not(is_online):
await channel.send(
f"<@&850539902675845170> Server Offline")
else:
await channel.send("Server Online")
was_online = is_online
如果您想在离线后退出循环:
@tasks.loop()
async def serverstatus():
channel=bot.get_channel(850531139403776040)
status=os.system("ping -c 1 "+ip)
if status:
await channel.send("Server Online")
else:
await channel.send(f"<@&850539902675845170> Server Offline")
serverstatus.stop()
推荐阅读
- javascript - 异步映射返回 Promise
- gnuplot - Gnuplot 错误消息:未定义变量通过
- node.js - jest js 手动模拟链式方法
- sql - SQL:将 Where 子句转换为内连接
- python-3.x - 使用python脚本在cassandra中导入csv文件
- javascript - Datatables 插件返回此错误 SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
- continuous-integration - 使用 ssh 密钥推送到 gitlab CI 中的多个 github 存储库
- typescript - 多级索引类型打字稿
- matlab - 在 Matlab 中向 OFDMA 系统添加噪声
- javascript - Ag grid node.setSelected(true) 不在 UI 上显示选中的复选框