Stopping Code Execution In Python

Friday, April 13, 2012 - 14:09

I am currently in the process of learning Python, so I thought I would start a series of mini blog posts detailing different things that I have found useful whilst learning how to use the language.

To stop code execution in Python you first need to import the sys object. After this you can then call the exit() method to stop the program running. It is the most reliable, cross-platform way of stopping code execution. Here is a simple example.

1
2
import sys 
sys.exit()

You can also pass a string to the exit() method to get Python to spit this out when the script stops. This is probably the preferred way of doing things as you might otherwise not realize where the script stopped. Obviously you wouldn't just stop the script running arbitrarily, but you might want to prevent it from running if certain conditions haven't been met. Here is another example that stops execution if the length of an array is less than 2.

1
2
3
4
5
6
7
8
import sys
 
listofitems = []
 
# Code here that does something with listofitems
 
if len(listofitems) < 2:
  sys.exit('listofitems not long enough')
Category: 
Tags: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Comments

1
2
import sys
the sys command doesn't come up in read

Very useful. thx. my game works better now u can die and it will not continue with other parts of the game.

Add new comment