gpt4 book ai didi

python - 如何通过 'try... except' 函数避免所有可能的错误

转载 作者:太空宇宙 更新时间:2023-11-04 01:07:14 26 4
gpt4 key购买 nike

我正在运行一个 python 代码来进行连续的网络抓取(在使用 Python 2.7 的 linux mint 上)。由于某些原因,代码有时会崩溃。到目前为止,我所做的是在发生错误时手动重新运行代码。

我想写另一个 python 代码来代替我做这个“检查状态,如果中断,然后重新运行”的工作。

我不知道从哪里开始。谁能给我一个提示?

最佳答案

你想要这样的东西:

from my_script import main

restart = True
while restart:
try:
main()
# This line will allow the script to end if main returns. Leave it out
# if you want main to get restart even when it returns with no errors.
restart = False
except Exception as e:
print("An error in main: ")
print(e.message)
print("Restarting main...")

这需要您的脚本,本例中的 my_script.py,设置如下:

def foo():
raise ValueError("An error in foo")

def main():
print("The staring point for my script")
foo()

if __name__ == "__main__":
main()

关于python - 如何通过 'try... except' 函数避免所有可能的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29740185/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com