问题
I have an f2py module that I am using. The core of the code I did not write myself, just the f2py wrapper to use it. Because of time constraints, and the knowledge that his code is short term need only, meaning I want to throw it away, not fix it, what I want to do is just catch the behavior when a segfault occurs and try again. The below code is an example:
sums.f90
subroutine bad(a, b, c)
real, intent(in) :: a, b
real, intent(out) :: c
real, allocatable :: d(:)
real :: r
call random_number(r)
if (r < 0.5) then
print *, d(1) ! segfault here
end if
c = a + b
end subroutine bad
compile with: f2py -c sums.f90 -m sums
and now if I just call it repeatedly, then sometimes it works and sometimes it doesn't.
>>> python -c "import sums; print(sums.bad(1,2))"
3.0
>>> python -c "import sums; print(sums.bad(1,2))"
3.0
>>> python -c "import sums; print(sums.bad(1,2))"
Segmentation fault: 11
>>> python -c "import sums; print(sums.bad(1,2))"
3.0
>>> python -c "import sums; print(sums.bad(1,2))"
3.0
>>> python -c "import sums; print(sums.bad(1,2))"
Segmentation fault: 11
Now I know the right thing to do is fix the segfault..., but I am hoping there is a way I can just handle it and move on from within the calling Python code. Is this possible?
来源:https://stackoverflow.com/questions/61831483/how-to-handle-occaisional-segmentation-fault-in-f2py-module