如何避免所有可能的错误'尝试。。。“除”功能

2024-04-23 20:16:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行一个python代码来执行连续的web废弃(在带有python2.7的linux mint上)。由于某些原因,代码有时会崩溃。到目前为止,我所做的是在出现错误时手动重新运行代码。你知道吗

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

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


Tags: 代码weblinux状态错误原因手动mint
1条回答
网友
1楼 · 发布于 2024-04-23 20:16:06

你想要这样的东西:

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()

相关问题 更多 >