如何获取Pandas发出的警告的行号

2024-04-18 18:36:54 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:

我有一些用Python编写的代码,并使用pandas生成和操作一些数据帧。在其中一些,我得到一些警告。例如,设置CopyWarning或performancewarning。我想捕捉发生警告的行no,为此,我编写了以下代码。我什么都听懂了,除了lineno。你知道吗

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

对于w[i].lineno,我期望行号。你知道吗

我得到的号码不属于原始文件。它属于python核心模块。我得到的是5312。 如何将行号追溯到我自己的脚本?你知道吗


Tags: 代码inpy警告forlenaswith
1条回答
网友
1楼 · 发布于 2024-04-18 18:36:54

msg.line丢失时,用来查找源代码行的warnings module uses ^{}。你知道吗

if msg.line is None:
    try:
        import linecache
        line = linecache.getline(msg.filename, msg.lineno)
        ...

你也可以这么做:

import warnings
import linecache
import numpy as np
import pandas as pd

with warnings.catch_warnings(record=True) as w:
    # Cause all warnings to always be triggered.
    warnings.simplefilter("default")

    # trigger a SettingWithCopyWarning
    df = pd.DataFrame(np.random.randint(10, size=(10,3)), columns=list('ABC'))
    subdf = df.iloc[::2]
    subdf.loc[:, 'A'] = 99

    for wi in w:
        if wi.line is None:
            wi.line = linecache.getline(wi.filename, wi.lineno)
        print('line number {}:'.format(wi.lineno)) 
        print('line: {}'.format(wi.line))

印刷品

line number 633:
line:                     self.obj[item_labels[indexer[info_axis]]] = value

相关问题 更多 >