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

Python 如何回溯警告以获取发生警告的行号?,python,pandas,logging,warnings,traceback,Python,Pandas,Logging,Warnings,Traceback,我有一些用Python编写的代码,并使用pandas制作和操作一些数据帧。在其中一些案例中,我得到了一些警告。例如,设置CopyWarning或performancewarning。我想捕捉发生警告的行号,为此,我编写了以下代码。除了行号之外,我什么都听懂了 scripts = ['myfile.py', 'myotherfile.py'] with warnings.catch_warnings(record=True) as w: # Cause all warnings to al

我有一些用Python编写的代码,并使用pandas制作和操作一些数据帧。在其中一些案例中,我得到了一些警告。例如,设置CopyWarning或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))
此外,我还将
警告。simplefilter(“默认”)
更改为
警告。simplefilter(“错误”)
以跟踪它们。但是,它仅在第一个异常发生时起作用。这是合乎逻辑的,但我希望对所有警告进行完整的跟踪。顺便说一下,当警告时间为
performancewarning

try:
    exec(f.read())     
except Exception:
    lg.getLogger("error_logger").error(traceback.format_exc())

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

这是否回答了您的问题。这回答了你的问题吗。