在脚本中执行脚本但继续处理错误并将其保存到文件

时间:2013-08-12 23:59:21

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

如果我要使用以下代码:

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

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

任何人都有任何想法或线索?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

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