csv - How to write out line of error for error exception (as well as actual error) in Python -
i running script fails lot on cron jobs. has issues encoding (utf etc) i'm trying sort , head around. i've made script writes errors out csv when crop up, fine, doesn't tell me line error happening on, struggling find out put .encode('utf-8')
in sort out problem. can tell me if there's way add error writing function line of error too?
the function use catch errors (for other bits of code too) follows...
def error_output(error): t = datetime.now().strftime('%y-%m-%d %h:%m:%s') new_data = [t, error] f = open('outputs/errors.csv', 'a') csv.writer(f, lineterminator='\n').writerows([new_data]) f.close()
...and script uses thus:
if condition: try: except exception e: error_output(e)
...this works nicely give me csv tells me things like:
2017-08-19 23:58:47 'ascii' codec can't encode character u'\u2019' in position 69: ordinal not in range(128) 2017-08-20 00:10:46 failed send request: 'utf8' codec can't decode byte 0xf0 in position 136: invalid continuation byte
...but i'd more technical description of error, i'd know in code happening, because i've peppered strings .encode('utf-8')
, still fails need know error (much if running script terminal - do, error happens of time, when dealing strange characters or emoji etc.).
any massively appreciated it's frustrating issue. thanks!
you may use traceback
>>> import traceback >>> >>> def f(): ... if true: ... 1 / 0 ... >>> try: ... f() ... except: ... print(traceback.format_exc()) ... traceback (most recent call last): file "<stdin>", line 2, in <module> file "<stdin>", line 3, in f zerodivisionerror: integer division or modulo 0
Comments
Post a Comment