问题
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?
回答1:
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)
回答2:
How about trying to import the modules inside a subprocess ?
E.g. subprocess.call("python -c 'import module_or_modules_in_question'")
Or you can start an multiprocessing job and import modules one by one in a separate job.
回答3:
As noted in vartecs answer, you cannot ordinarily catch a segmentation fault. However, if you are looking to debug code that fails with a segmentation fault and you're not sure where it happens, you can use the faulthandler module, available since Python 3.3. This will not catch the error, but it will at least display a traceback, which may help you to pinpoint the origin. From the documentation:
$ python3 -c "import ctypes; ctypes.string_at(0)" Segmentation fault $ python3 -q -X faulthandler >>> import ctypes >>> ctypes.string_at(0) Fatal Python error: Segmentation fault Current thread 0x00007fb899f39700 (most recent call first): File "/home/python/cpython/Lib/ctypes/__init__.py", line 486 in string_at File "<stdin>", line 1 in <module> Segmentation fault
来源:https://stackoverflow.com/questions/10929162/how-can-i-catch-a-seg-fault-while-importing-an-f2py-module