【发布时间】:2021-06-28 16:30:14
【问题描述】:
我有一个脚本main.py,它运行目录中其他脚本的一些函数。如果特定功能运行正确或失败(即错误处理),我有一个非常原始的想法,即向自己发送 Slack 通知。 我将如何使用位于单独脚本中的错误处理函数 - 在我的 main.py 脚本中调用文件 slack_notifications.py? This linked 问题开始得到答案,但它没有不要从其他地方调用错误函数。
main.py脚本:
import scraper_file
import slack_notifications
# picture scrape variable
scrape_object = 'Barack Obama'
# scraper function called
scraped_image = scraper_file.pic_scrape(scrape_object)
# error handling?
slack_notifications.scrape_status(scrape_object)
我已经尝试将调用的刮板函数嵌入到scrape_status() 函数中,像这样:scraped_image = (slack_notifications.scrape_status(scraper_file.pic_scrape(scrape_object))) 和其他一些方法,但这并不能真正告诉你它是否运行成功,对吧?
slack_notifications.py 脚本:
testing = "dunderhead"
def scrape_status(x):
# if this function gets a positive return from the scrape function
# if this function gets any error from the scrape function
try:
x
print(x + ' worked!')
except:
print(x + ' failed!')
if __name__ == '__main__':
scrape_status(testing)
有没有办法做到这一点?我也离开了these instructions。
【问题讨论】:
-
你的
scrape_status似乎完全没用。它将运行try/except太晚 - 在错误发生后 - 所以它无法捕获它。您必须将函数名称(不带())发送到scrape_status并与()一起使用以在try/except内执行它 - 然后它可以捕获它。或者只是你必须在try/except内运行scraper_file.pic_scrape(scrape_object),如果你直接在scraper_file.pic_scrape(scrape_object)内使用try/except而不是为scrape_Status()创建通用函数this会更简单 -
yoiur 中的代码首先起作用,因为函数
input()已从外部error_handler移动到内部error_handler并且您必须对scraper_file.pic_scrape(scrape_object)执行相同操作 - 您必须将其移动到 @ 987654348@ 但您不能使用scraper_file.pic_scrape(scrape_object)执行此操作,因为它在scrape_status之外运行。你所有的想法都过于复杂了。最好将所有代码放在一个文件中,不要尝试创建通用函数scrape_status
标签: python error-handling