如何追溯警告以获取发生的行号?

时间:2019-07-25 09:02:59

标签: python pandas logging warnings traceback

我有一些用Python编写的代码,并使用熊猫制作和操纵了一些DataFrame。在其中一些中,我得到了一些警告。例如settingwithcopywarning或performancewarning。我想捕获发生警告的 行号 ,为此,我编写了以下代码。除了行号以外,我什么都抓不到。

scripts = ['myfile.py', 'myotherfile.py']
with warnings.catch_warnings(record=True) as w:
    # Cause all warnings to always be triggered.
    warnings.simplefilter("default")
    for s in scripts:
        with open(s) as f:
            try:
                exec(f.read())
            except Exception as e:
                print('An Error happend during the execution', e)
            finally:    
                f.close()    

    print(color.orange('There are {} error/s happend in {}.'.format(len(w), s)))
    for i in range(0, len(w)):
        print(color.green('LineNo: '), w[i].lineno)
        print(color.green('Line: '), w[i].line)
        print(color.green('warning category: '), w[i].category.__name__)
        print(color.green('Warning: '), w[i].message) 
        print(color.green('filename: '), w[i].file) 
        print(color.cyan('-' * 40))

我也将warnings.simplefilter("default")更改为warnings.simplefilter("error")以追溯它们,但是,它仅在第一个异常发生时起作用。这是合乎逻辑的,但是我想获得所有警告的整个追溯。顺便说一句,警告时间为PerformnceWarning

时不起作用
try:
    exec(f.read())     
except Exception:
    lg.getLogger("error_logger").error(traceback.format_exc())

我希望获取原始文件的行号,而不是警告记录的python核心模块

0 个答案:

没有答案