4 回答
TA贡献1795条经验 获得超7个赞
你可以通过设置一个标志来做到这一点。如果您遍历文件但没有找到匹配项,则标志保持为假。
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()
TA贡献2021条经验 获得超8个赞
干得好。无需单独调用 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 False
def send_email():
blah blah blah
if not main_function():
send_email()
TA贡献1865条经验 获得超7个赞
您可以将匹配成功保存在一个变量中,如果变量没有因匹配而改变,则调用该函数:
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()
TA贡献1775条经验 获得超8个赞
下面的脚本怎么样:
try:
main_function
except:
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 success
def send_email():
blah blah blah
main_function_success = main_function()
if not main_function_success:
send_email
添加回答
举报