4 回答

TA貢獻(xiàn)1795條經(jīng)驗(yàn) 獲得超7個(gè)贊
你可以通過(guò)設(shè)置一個(gè)標(biāo)志來(lái)做到這一點(diǎn)。如果您遍歷文件但沒(méi)有找到匹配項(xiàng),則標(biāo)志保持為假。
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貢獻(xiàn)2021條經(jīng)驗(yàn) 獲得超8個(gè)贊
干得好。無(wú)需單獨(dú)調(diào)用 main_function。當(dāng)您評(píng)估條件“not main_function()”時(shí),它將被調(diào)用。
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貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以將匹配成功保存在一個(gè)變量中,如果變量沒(méi)有因匹配而改變,則調(diào)用該函數(shù):
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貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊
下面的腳本怎么樣:
try:
main_function
except:
send_email
這樣,如果 main_function 函數(shù)拋出錯(cuò)誤,python 將捕獲它,并調(diào)用 send_email 函數(shù)。
或者,如果您不希望 main_function 因拋出錯(cuò)誤而失敗,您可以執(zhí)行以下操作:
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
添加回答
舉報(bào)