【问题标题】:How to avoid all possible errors by 'try... except' function如何通过“尝试...除外”功能避免所有可能的错误
【发布时间】:2015-06-26 17:22:31
【问题描述】:

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

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

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

【问题讨论】:

  • 我的代码中有几个 try except 块。由于有很多不同的方法可以得到错误,我无法穷举所有可能的错误。这就是为什么我想使用代码让自己从手动重新运行代码中解放出来。

标签: python process monitor status running-other-programs


【解决方案1】:

你想要这样的东西:

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

【讨论】:

  • 这太棒了!我正在使用这段代码,到目前为止效果很好。但是,我不明白代码是如何工作的。能否请您简要解释一下?
  • 您能不能更具体地说明您不了解的内容。您可能只想阅读 how try/except works in Python 作为起点。
  • 我不明白 foo() 和 main() 函数是如何工作的。或者更具体地说,if __name__ == "__main__" 条件是什么意思?我没有看到 name 变量在代码中的任何位置定义。
  • foomain 只是函数,没有什么特别之处。我包含两个函数只是为了表明只有 1 个函数,即脚本的入口点,需要导入。 if __name__ == "__main__": main() 在这里无关紧要,您可以忽略它。我把它放进去是因为它被一些人常用在 python 脚本中。 Here is a post 符合 if __name__ == "__main__": 的目的。
  • 现在我更好地理解了代码。但是,我发现它与我真正想做的事情有所不同。在您(Bi Rico)编写的代码中,它在my_script() 中引发错误,因此第一个代码一遍又一遍地重新启动my_script。我需要的是让my_script尽可能长时间地运行,当发生内在错误时,其他代码可以重新启动它。
猜你喜欢
  • 1970-01-01
  • 2015-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-27
  • 1970-01-01
  • 2023-01-17
  • 2019-07-31
相关资源
最近更新 更多