【问题标题】:How to check if a function ran without generating any errors如何检查函数是否运行而不产生任何错误
【发布时间】:2021-06-15 15:41:08
【问题描述】:

我想检查 message() 函数是否正确运行并设法发送消息,用户可能在一段时间内无法访问,所以我想编写脚本跳过他没有管理的名字向他发送消息,并标记发送消息的人的姓名

我试图设置一个布尔值 函数运行后会发生变化,但它似乎不起作用,我正在使用模块发送消息我在模块而不是脚本本身上收到错误

user_was_messaged = False

def message_user()
    user_was_messaged = True

【问题讨论】:

  • 什么是模块化?
  • 你能从函数中返回一个布尔值吗?然后,如果函数返回 False,您可以将用户添加到您的列表中。
  • 如果您的问题在于根据您使用的库引发的错误来识别消息是否已发送,请查看 try/except 块
  • 你能澄清你在问什么吗?如果一个函数“结束”时出现错误,一个异常将贯穿所有外部函数,除非你主动抑制它。

标签: python python-3.x function boolean


【解决方案1】:

如果您的user_was_messaged 变量是全局变量,那么您需要使用global Python 语句从您的函数中更改值:

user_was_messaged = False

def message_user():
    global user_was_messaged
    user_was_messaged = True

但是,强烈建议不要为此使用全局变量。而是使用函数的返回值:

def message_user():
    # do things to try to send a message
    if cannot send:
        return False
    # maybe do more things
    return True

if message_user():
    print("successful")
else:
    print("failed")

【讨论】:

    【解决方案2】:

    由于您在函数之前有变量user_was_messaged,因此您必须在函数中将变量声明为全局变量,如下所示:

    user_was_messaged = False
    
    def message_user()
        global user_was_messaged
        user_was_messaged = True
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 2017-02-26
      • 2016-03-10
      • 2021-05-30
      • 1970-01-01
      • 2017-07-21
      • 2019-12-16
      相关资源
      最近更新 更多