python tracing a segmentation fault

I'm developing C extensions from python and I obtain some segfaults (inevitable during the development...).

I'm searching for a way to display at which line of code the segfault happens (an idea is like tracing every single line of code), how can I do that?


If you are on linux, run python under gdb

gdb python
(gdb) run /path/to/script.py
## wait for segfault ##
(gdb) backtrace
## stack trace of the c code

Here's a way to output the filename and line number of every line of Python your code runs:

import sys

def trace(frame, event, arg):
    print("%s, %s:%d" % (event, frame.f_code.co_filename, frame.f_lineno))
    return trace

def test():
    print("Line 8")
    print("Line 9")

sys.settrace(trace)
test()

Output:

call, test.py:7
line, test.py:8
Line 8
line, test.py:9
Line 9
return, test.py:9

(You'd probably want to write the trace output to a file, of course.)