【问题标题】:Executing a script within a script but continuing on error(s) and saving them to file在脚本中执行脚本但继续出错并将它们保存到文件
【发布时间】:2013-08-12 23:59:21
【问题描述】:

如果我有以下代码:

try: 
    execfile("script.py")
except ## unsure what exception goes here...
    continue:
try: 
    execfile("other.py")
except ## unsure what exception goes here...
    continue:

如何捕获 script.py 中的所有错误并将其保存到文件中,然后继续执行下一个调用的脚本

有人有什么想法或线索吗?

【问题讨论】:

  • 用一些在文件上写入错误的代码替换“继续”?
  • @GiwrgosTsopanoglou 我不确定如何做那部分,错误的捕获是我被卡住的地方。就像这里的情况一样,真正简单的事情有时可能太明显了。
  • 是的,我知道你的意思。我认为 rogaos 给出的答案让你陷入困境:)

标签: python python-2.7 error-handling try-except execfile


【解决方案1】:
errors = open('errors.txt', 'w')
try: 
    execfile("script.py")
except Exception as e:
    errors.write(e)
try: 
    execfile("other.py")
except Exception as e:
     errors.write(e)
errors.close()

【讨论】:

  • 嗯,这比我预期的要容易。非常感谢您,点赞并接受您的回答:)
【解决方案2】:
import traceback # This module provides a standard interface to extract, 
                 # format and print stack traces of Python programs.

try: 
    execfile("script.py")
except:
    traceback.print_exc(file=open('script.traceback.txt', 'w')) # Writing exception with traceback to file script.traceback.txt

# Here is the code that will work regardless of the success of running a script.py

【讨论】:

  • 很有趣的方法,我会用它和 rogoas 的版本。
猜你喜欢
  • 2016-08-19
  • 1970-01-01
  • 2020-10-13
  • 2011-08-22
  • 1970-01-01
  • 2017-05-09
  • 1970-01-01
  • 2021-02-20
  • 1970-01-01
相关资源
最近更新 更多