如何根据另一个函数的成功或失败来执行一个函数?

我有一个主要功能,它从用户输入中搜索带有 2 个关键字的 txt 文件,如果找到它,它将打印 txt 文件中的行。


我想编写另一个函数(send_email),如果主函数在文件中找不到匹配的任何内容,它就会执行,我们将不胜感激。


def main_function():

  with open("file.txt", "r") as f:

    for line in f.readlines():

      if line.startswith(area) and name in line:

        print("\n" + "\n" + "SPP Location:" + "\n" + line + "\n")


main_function()




def send_email():

  blah blah blah



if main_function is False:

   send_email


料青山看我应如是
浏览 111回答 4
4回答

一只萌萌小番薯

你可以通过设置一个标志来做到这一点。如果您遍历文件但没有找到匹配项,则标志保持为假。def main_function():  with open("file.txt", "r") as f:    find_flag = False    for line in f.readlines():      if line.startswith(area) and name in line:        print("\n" + "\n" + "SPP Location:" + "\n" + line + "\n")        find_flag = True    if not find_flag:        send_email()

宝慕林4294392

干得好。无需单独调用 main_function。当您评估条件“not main_function()”时,它将被调用。def main_function():    with open("file.txt", "r") as f:        for line in f.readlines():            if line.startswith(area) and name in line:                print("\n" + "\n" + "SPP Location:" + "\n" + line + "\n")                return True    return Falsedef send_email():    blah blah blahif not main_function():    send_email()

莫回无

您可以将匹配成功保存在一个变量中,如果变量没有因匹配而改变,则调用该函数:def main_function():    with open("file.txt", "r") as f:        results = 0        for line in f.readlines():            if line.startswith(area) and name in line:                print("\n" + "\n" + "SPP Location:" + "\n" + line + "\n")                results = 1        if results == 0:            send_email()

www说

下面的脚本怎么样:try:    main_functionexcept:    send_email这样,如果 main_function 函数抛出错误,python 将捕获它,并调用 send_email 函数。或者,如果您不希望 main_function 因抛出错误而失败,您可以执行以下操作:def main_function():    success = False    with open("file.txt", "r") as f:    for line in f.readlines():      if line.startswith(area) and name in line:        print("\n" + "\n" + "SPP Location:" + "\n" + line + "\n")                success = True    return successdef send_email():  blah blah blahmain_function_success = main_function()if not main_function_success:   send_email
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python