我正在运行 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/