+ 4
Why do I need sys.exit()?
When running a script from the command line, why do I need "sys.exit()"? Can anyone please explain this to me with an example? Python documentation can be a bit hard to read sometimes, at least for me 😅
8 odpowiedzi
+ 5
But what is it for? When would I need it?
+ 5
For example:
a = int(input())
b = int(input ())
if(b!=0):
print("a/b:",a/b)
else:
print("Error: You can't divide by zero. we will force to close the program, sorry...")
sys.exit()
# Do something if everything is ok...
+ 5
Ahhh, ok, so I don't HAVE to use it, I CAN use if for whatever reason it's useful for my goal to exit the script, it's just another tool...
Thank you Rolando for your answers and for your patience!!! I really appreciate it 👍😃
+ 4
Ok, good example, doesn't Python finish executing the program anyway? Why is it necessary to write "sys.exit()", to make it explicit? (Sorry for my insistence, but I can't find the answer, I guess it's too basic for Stackoverflow 😅)
+ 3
You don't need sys.exit().
Use this when you want to stop your script.
+ 3
A slightly more technical example: You are from a Shell and want to run a Python script, but you need to know if everything went well. One way to know if everything was executed correctly is to see some value that your script returns. Not only can you go out with sys.exit (), you can also go out with a custom value like sys.exit (1) or sys.exit (999) and use that value returned by your program to do one or another action from your shell.
+ 2
Rolando A. Rosales J. has said it all
0
Hi