0

I use some Python libraries that rely on Python bindings to execute code in other language. Sometimes the execution of the underlying code fails and seems to force stop my Python run. try and except fail to capture this type of termination.

Is there a simple way to capture any such early termination of my code in Python (or ideally, any termination other than CTRL+C)?

Thank you very much for your help

Vincent
  • 105
  • 7

1 Answers1

1

You don't mention the platform. On Linux/Unix/Mac most runtime errors result in signal which is generated by the OS. You will have to use the python signal package to catch the signals. There are a couple of signals where the OS will kill your processes and you can't catch them. These are the SIGKILL and SIGSTOP. You also can't catch a SIGSEG when running out of allowed stack memory. But other such as segmentation faults and bus errors can be caught.

It may also be some other error in the library, where the code library is explicitly killing the process (e.g. calling exit()). In that case you are out of luck as far as I know.

codegen
  • 118
  • 5
  • Thank you all for your help. I am working with Mac, but I would like the code to work in other platforms as well. I have looked into the signal module, and it seems that a SIGKILL signal is being raised. Is it possible to call the function in a separate process, so that if SIGKILL is raised it does not interrupt the execution of my main program? – Vincent Jan 11 '22 at 18:56
  • Hard to say without any more information. You can always write a separate program that uses the code you are calling from python, but you would have to manage the communication with that other program, and also deal with restarting the other program if it fails for some reason. Alternatively, you can find out why the SIGKILL is happening. If it only occurs for specific input, you can sanitize your parameters before calling it to prevent the failure.' – codegen Jan 12 '22 at 19:19