I have some codes written in Python and used pandas to make and manipulate some DataFrames. In a few of them, I get some warnings. for example settingwithcopywarning or performancewarning. I want to catch the line number that warning has occured and for that, I wrote the following code. I catch everything but the line number.
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))
also I changed the warnings.simplefilter("default")
to warnings.simplefilter("error")
to trace them back however, it works just when the first exception happens.which is logical but I want to get the whole traceback for all warnings. by the way, that does not work when the warning time is PerformnceWarning
try:
exec(f.read())
except Exception:
lg.getLogger("error_logger").error(traceback.format_exc())
I expect to get the line number for the original file not the python core modules that the warnings logged