Search code examples
pythonimportmodulesegmentation-faultf2py

How can I "catch" a seg fault while importing an F2Py module?


Some background, the relevance of which may fluctuate:

I am currently in possesion of some F2Py libraries - Python modules compiled by F2Py from some Fortran code. For all intents and purposes, you can regard these modules as "third party"; I currently do not have access to the Fortran source code, and I am not in charge of the compilation process.

The modules themselves are imported into a program I am helping to develop that has Python scripting support and that runs on multiple platforms.

I am trying to guard against future crashes arising from compatibility issues caused by the library versions on the compilation machine and the user's machines becoming out of sync. A problem has already occured where one of our user's machines had changed to an incompatible version of numpy, and this caused an unacceptable seg fault at startup when the module was imported.

The question:

I am looking for a way to import F2Py modules, but in such a way so that I can deal with any seg faults that may occur because of incompatible library versions that modules may depend on. I currently check for numpy version before calling import, but I would rather import first and then "catch" any problems later:

try:
    import module_name
except SegFault:
    # Deal with it.

Is catching seg faults - specifically as a result of importing - at all possible?


Solution

  • Segfault is not an exception, it's a signal. You can "catch" signals by assigning handlers to them.

    import signal
    
    def sig_handler(signum, frame):
        #deal with the signal.. 
    
    signal.signal(signal.SIGSEGV, sig_handler)