Why Stop a Python Script?
As a programming language,Python is designed to read code line by line and stop at the end of the script by default – so why would we need to stop it?
Whilst there are a number of reasons this may be necessary, they basically fall into two distinct categories:
- You have made an error with your code, for example the program keeps running in an infinite, or at least very long, loop (anyone who has used Python can probably relate to this!)
- The code itself is correct, but you want to stop your script from running if certain conditions either have or have not been met.
Option 2 can be planned for by including a stop mechanism within our code, i.e. programmatically. For option 1, we need to understand how to stop our code arbitrarily when the program is running, and we do this using our keyboard. Let’s have a look at these two options in more detail.
Keyboard Stops
The exact mechanism for a keyboard stop will really depend on your operating system, for the purposes of this article we are going to be using a Windows 10 machine so all syntax will relate to this environment.
To start with, let’s put together a little script that will give us the problem we are looking to solve, and call it test.py
and save it in a working directory C:\Users\Rikesh
:
x = 1 while x >= 1: print (x) x = x +1
If we now run the above script through our Python interpreter it will just keep printing numbers sequentially indefinitely. We have not put any conditions on it to stop.
C:\Users\Rikesh> test.py 1 2 3 4 ..
Keyboard Interrupt
One of the most common methods to stop a script is by using the following keyboard shortcut, which is known as KeyboardInterrupt :
Ctrl + C
When we use this we get a response back from our Python interpreter telling us the program was stopped using this shortcut.
.. 2396 2397 2398 Traceback(most recent call last): File “C:Users\Rikesh .. “ KeyboardInterrupt
2.2 Ctrl + Pause / Break
Whilst the above works well with our simple code example, there are times when this might not be the case. For example, our script could explicitly stop this from working by specifically excluding KeyboardInterrupt i.e except KeyboardInterrupt or it can even be excluded with the normal except syntax. For example:
x = 1 while x >= 1: try: print (x) x = x +1 except: pass
The effect of except:, in this example, is to negate our KeyboardInterrupt shortcut – whether intentionally or not. So now, when we run the above script through our windows command prompt, our ctrl + c shortcut is ineffective and the numbers keep printing.
C:\Users\Rikesh> test.py 1 2 3 4 5 6 ..
In this instance we can use Ctrl + Pause/Break which is a much more powerful way of stopping our script.
.. 2396 2397 ˄c C:\Users\Rikesh>
Not only does this stop the script, but as this is not the KeyboardInterrupt
shortcut we don’t get the same message back from our interpreter. We are simply returned to the command prompt.
Programmatic Stops
So we have seen how to use our keyboard to stop our scripts from running, now let’s look at how we can use our code to stop the scripts. This will obviously require us to understand our code and pre-determine where any stops will be necessary.
Programmatically in Development Code
When you start Python the site module is automatically loaded, and this comes with the quit() and exit()objects by default. These two objects work in the same way, as follows, and as their names suggest can be used to stop our scripts:
x = 1 while x >= 1: print (x) x = x +1 if x >= 5: quit()
x = 1 while x >= 1: print (x) x = x +1 if x >= 5: exit()
In both instances, if we run the code above from our interpreter the program will automatically stop and exit/quit once x gets to 5.
C:\Users\Rikesh> test.py 1 2 3 4 C:\Users\Rikesh>
However, please note both quit()
and exit()
are only designed for use within the Python interpreter, where the site module has been loaded. Neither of these are deemed suitable for use in production code, i.e in a real-world situation, as we are not controlling how and if the site module is loaded. For this reason, both of these options should only be used for development purposes and within the Python interpreter.
Programmatically in Production Code
So now let’s look at how we can stop our scripts from running in production code. To clarify, by this we mean the code that is ready to be sent to the client / end-user. It has been debugged, and is well-structured and well-documented.
Using sys.exit()
This is the most common way of stopping our scripts programmatically, and it does this by throwing/raising a SystemExit exception. If the exception is not caught the Python interpreter is closed and the program stops. As we need to explicitly import the sys module we make sys part of our script effectively guaranteeing it will always be there when the code is run. This makes this method ideal for use in our production code:
import sys x = 1 while x >= 1: print (x) x = x +1 if x >= 5: sys.exit()
Now by running the script we get the following output:
C:\Users\Rikesh> test.py 1 2 3 4 C:\Users\Rikesh>
Whilst the end result is the same as before, with quit()
and exit()
, this method is considered to be good practice and good coding. Because we have imported the sys module within our script, it will always be available when the script is run..
raise SystemExit
This is interesting because, whilst it does everything that sys.exit()
does, it does not appear to be commonly used or considered best practice. This has the advantage of not requiring any import and all the sys.exit()
operation does, as we saw in the previous section, is to raise a SystemExit
exception anyway. Therefore there is an argument, that by using this method, we are making our code cleaner and more efficient:
x = 1 while x >= 1: print (x) x = x +1 if x >= 5: raise SystemExit
And when we run the code, the output is as follows :
C:\Users\Rikesh> test.py 1 2 3 4 C:\Users\Rikesh>
Using os._exit()
The last method we will look at is os._exit()
which is part of the Python os
module providing functions for interacting directly with the operating system. This method basically calls for the immediate program termination, rather than raising an exception, so is possibly the most extreme of all we have seen.
Practical usage is therefore limited to very specific cases, so for the purposes of this article, we will concentrate on how to use it rather than why and when. Firstly, we have to import the os
module for it to work, and unlike the other methods we have seen we can not pass an empty parameter. This means we need to specify the exit status taking place, which is normally an integer value, with 0 being a normal exit. If we assume that to be the case our code will look like this:
import os x = 1 while x >= 1: print (x) x = x +1 if x >= 5: os._exit(0)
And when we run the code, the output is as follows :
C:\Users\Rikesh> test.py 1 2 3 4 C:\Users\Rikesh>
Summary
We have seen a number of methods for stopping our Python scripts, which should not come as a surprise for anyone familiar with Python. Whilst they all provide the same end result they do have different applications, particularly between using your keyboard or stopping programmatically with your code.
Even within the various programmatic ‘stops’ the most appropriate method will really depend on whether you are writing code for development or production purposes. Whilst the practical use of os._exit()
is limited, sys.exit()
is certainly considered to be best practice with production code. In my opinion, however, there is a strong case for using the raise SystemExit
approach. It appears the cleanest and most logical of all methods, and is less dependent on external libraries – all the same attributes that make Python such a versatile language.