+ 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 😅

5th Dec 2019, 12:52 AM
Alina Sansevich
Alina Sansevich - avatar
8 Respuestas
+ 5
But what is it for? When would I need it?
5th Dec 2019, 5:00 AM
Alina Sansevich
Alina Sansevich - avatar
+ 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...
5th Dec 2019, 5:05 AM
Rolando A. Rosales J.
Rolando A. Rosales J. - avatar
+ 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 👍😃
5th Dec 2019, 11:51 AM
Alina Sansevich
Alina Sansevich - avatar
+ 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 😅)
5th Dec 2019, 5:38 AM
Alina Sansevich
Alina Sansevich - avatar
+ 3
You don't need sys.exit(). Use this when you want to stop your script.
5th Dec 2019, 4:58 AM
Rolando A. Rosales J.
Rolando A. Rosales J. - avatar
+ 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.
5th Dec 2019, 6:32 AM
Rolando A. Rosales J.
Rolando A. Rosales J. - avatar
+ 2
Rolando A. Rosales J. has said it all
16th Dec 2019, 1:31 AM
Dace [Super Inactive| Challenge=Maybe]
Dace [Super Inactive| Challenge=Maybe] - avatar
0
Hi
6th Dec 2019, 2:17 PM
Mohammed Mogaji
Mohammed Mogaji - avatar