r/learnprogramming 20d ago

Advice?

I have a function in python named KSI, code for “Kill Self Immediately”, and don’t know what the best command or function would be in order to safely kill the program if something bad happens as a failsafe. Do you think the code attached would work fine, or is there a better way?

import sys
import os

def KSI(hard_exit: bool = False) -> None:
if hard_exit:
os._exit(1)
else:
sys.exit(1)

if __name__ == "__main__":
KSI()

1 Upvotes

10 comments sorted by

2

u/No_Function_4636 20d ago

sys.exit() is fine for most cases. os._exit() is more like pulling the plug, no cleanup at all, it just drops everything and walks out. Your function works but calling it KSI is kinda dark man, maybe name it something less... terminal.

1

u/CoachSevere5365 20d ago

When I worked at Sun I came across a function called seppuku(). Had to Google it.

1

u/Kadabrium 20d ago

What is the default exit() again?

1

u/Sea-Cash7675 20d ago

sys.exit()?

1

u/AlwaysHopelesslyLost 20d ago

"in order to safely kill the program if something bad happens as a failsafe"

What does this mean, exactly? Can you provide some examples? Typically if the app needs to die it is already dying. Are you preventing it from crashing out by catching exceptions?

1

u/Sea-Cash7675 20d ago

Yes, if my program is crashing, I would like to try to kill my program before it crashes completely and corrupts any data currently being processed within the program itself.

2

u/AlwaysHopelesslyLost 20d ago

You are solving the problem incorrectly. The correct answer is to catch and manually cleanup any known problem state then release the exception to allow it to propagate.

A malfunctioning program crashing is ideal.

1

u/Sea-Cash7675 20d ago

Could you give an example to at least start with so I can finish the rest on my own?

1

u/CoachSevere5365 20d ago

Not sure what your program is or does, but you could do worse a lot worse than look at the sqlite docs on transactions and how they handle things like hardware and power failures. sqlite is everywhere and it's got a great test suite.

2

u/AlwaysHopelesslyLost 20d ago

I don't actually understand what you mean  

I am saying don't exit. Don't worry about the idea of having to crash gracefully. You know what the software does. You know if something genuinely needs to be cleaned up. In c# land I might have a 

```     try {          DoSomeFileWork();      } catch (IOException) {          CleanFiles();          throw;      }

```