You need to enable JavaScript to run this app. Python代码同一触发条件下输出两次打印结果 如何修改为仅输出单次结果
优惠活动
大模型
产品
解决方案
定价
更多

Python代码同一触发条件下输出两次打印结果 如何修改为仅输出单次结果

重复触发双告警问题的修正方案

核心问题根源

  • 逻辑边界未划清:当前代码中写在if-else结构外的通用告警代码,不受分支判断控制。哪怕已经在paribu的判断分支里执行完专属告警的打印、消息发送流程,程序走完分支块后,还是会无差别执行块外的通用告警代码,最终造成同一触发条件下输出两条告警的问题。
  • 存在冗余赋值:else分支内重复定义的alert_message,和外层提前定义的通用告警消息内容完全一致,属于无意义的代码。

调整思路

  • 把两类告警的完整执行流程(打印、触发告警、Telegram消息发送、等待10秒)分别收拢到对应的if、else分支内部,保证走哪个分支就完整执行对应分支的全部逻辑,既不会漏执行也不会多执行。
  • 删除else分支内无意义的重复赋值,精简代码结构。

修正后可直接使用的代码

current_threshold = (max_bid_val - min_ask_val) * 100 / min_ask_val

if current_threshold > threshold:
    # 提前定义两类告警模板
    base_alert_message = "Buy " + coin_list[i] + " on " + min_ask_place + " website for " + str(
        min_ask_val) + " price and Sell on " + max_bid_place + " for " + str(max_bid_val) + " price."
    paribu_alert_message = "Buy " + coin_list[i] + " on " + min_ask_place + " website for " + str((
        min_ask_val * paribu_dic[symbol_usdt_tl]['highestBid'])) + " price and Sell on " + max_bid_place + " for " + str(
        max_bid_val) + " price."

    if 'paribu' in min_ask_place:
        # Paribu渠道专属告警全流程
        print(paribu_alert_message)
        start_alert(paribu_alert_message)
        telegram_send.send(messages=[paribu_alert_message])
        time.sleep(10)
    else:
        # 非Paribu渠道通用告警全流程
        print(base_alert_message)
        start_alert(base_alert_message)
        telegram_send.send(messages=[base_alert_message])
        time.sleep(10)

实用小优化

  • 拼接告警消息时可以用f-string替代手动字符串拼接,减少str()类型转换的重复代码,也能降低拼接出错的概率,比如通用告警可以简化为:f"Buy {coin_list[i]} on {min_ask_place} website for {min_ask_val} price and Sell on {max_bid_place} for {max_bid_val} price."
  • 原代码判断条件外层的括号在Python语法中是冗余的,去掉后不影响程序运行,代码会更简洁。

内容的提问来源于stack exchange,提问作者hasan cetin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.24 09:54:03