I have added a small debugging aid to my server. It logs a stack trace obtained from traceback.format_stack()
It contains few incomplete lines like this:
File "/home/...../base/loop.py", line 361, in run
self.outputs.fd_list, (), sleep)
which is not that much helpfull.
The source lines 360 and 361:
rlist, wlist, unused = select.select(self.inputs.fd_list,
self.outputs.fd_list, (), sleep)
If only one line can be part of the stack trace, I would say the line 360 with the function name (here select.select
) is the right one, because the stack is created by calling functions.
Anyway, I would prefer the whole (logical) line to be printed. Or at least some context (e.g. 2 lines before). Is that possible? I mean with just an adequate effort, of course.
Tried to add a line continuation character \
, but without success.
EPILOGUE: Based on Jean-François Fabre's answer and his code I'm going to use this function:
def print_trace():
for fname, lnum, func, line in traceback.extract_stack()[:-1]:
print('File "{}", line {}, in {}'.format(fname, lnum, func))
try:
with open(fname) as f:
rl = f.readlines()
except OSError:
if line is not None:
print(" " + line + " <===")
continue
first = max(0, lnum-3)
# read 2 lines before and 2 lines after
for i, line in enumerate(rl[first:lnum+2]):
line = line.rstrip()
if i + first + 1 == lnum:
print(" " + line + " <===")
elif line:
print(" " + line)
File "file", line N, in func
in the first line and a corresponding source code line in the second line. – Wolof