Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Stop a Python Script (Keyboard and Programmatically)

#1
How to Stop a Python Script (Keyboard and Programmatically)

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:

  1. 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!) 
  2. 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.

The post How to Stop a Python Script (Keyboard and Programmatically) first appeared on Finxter.



https://www.sickgaming.net/blog/2021/02/...matically/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python Get Milliseconds xSicKxBot 0 41 02-19-2021, 08:28 AM
Last Post: xSicKxBot
  [Tut] Python str() Function xSicKxBot 0 35 02-14-2021, 06:05 AM
Last Post: xSicKxBot
  [Tut] Python issubclass() xSicKxBot 0 39 02-12-2021, 10:40 AM
Last Post: xSicKxBot
  [Tut] Python int() Function xSicKxBot 0 45 02-04-2021, 08:21 PM
Last Post: xSicKxBot
  [Tut] How To Cut A String In Python? xSicKxBot 0 35 02-01-2021, 04:09 PM
Last Post: xSicKxBot
  [Tut] Python filter() xSicKxBot 0 54 02-01-2021, 03:25 AM
Last Post: xSicKxBot
  [Tut] Python help() xSicKxBot 0 41 01-22-2021, 01:02 AM
Last Post: xSicKxBot
  [Tut] Python globals() xSicKxBot 0 45 01-19-2021, 04:16 AM
Last Post: xSicKxBot
  [Tut] Python getattr() xSicKxBot 0 53 12-28-2020, 05:11 AM
Last Post: xSicKxBot
  [Tut] Python delattr() xSicKxBot 0 54 12-26-2020, 12:06 AM
Last Post: xSicKxBot

Forum Jump:

[-]
Active Threads
[1.07] BO4 Zombie Trainer (Semi-Patched)
Last Post: Appledryck
Today 09:39 AM
» Replies: 13
» Views: 512
[1.06] BO4 Zombie Trainer (Call of duty ...
Last Post: Appledryck
Today 09:37 AM
» Replies: 55
» Views: 2532
[Tut] What’s the Double Colon :: Operato...
Last Post: xSicKxBot
Today 09:30 AM
» Replies: 0
» Views: 1
(Indie Deal) Quantum Break, State of Dec...
Last Post: xSicKxBot
Today 09:30 AM
» Replies: 0
» Views: 2
Checked C Language
Last Post: xSicKxBot
Today 09:29 AM
» Replies: 0
» Views: 2
AppleInsider - Apple sends out $500 prom...
Last Post: xSicKxBot
Today 09:29 AM
» Replies: 0
» Views: 1
Microsoft - What’s new in Microsoft Edge...
Last Post: xSicKxBot
Today 09:29 AM
» Replies: 0
» Views: 1
News - Random: ‘Amogus’ Is A Playable Am...
Last Post: xSicKxBot
Today 09:29 AM
» Replies: 0
» Views: 1
News - Blaster Master Zero 3 Explodes On...
Last Post: xSicKxBot
Today 09:29 AM
» Replies: 0
» Views: 1
News - Fortnite: When Does Season 6 Star...
Last Post: xSicKxBot
Today 09:29 AM
» Replies: 0
» Views: 2

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020