Stopping Code Execution In Python

13th April 2012

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. import sys
  2. 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. import sys
  2.  
  3. listofitems = []
  4.  
  5. # Code here that does something with listofitems
  6.  
  7. if len(listofitems) < 2:
  8. sys.exit('listofitems not long enough')

 

Comments

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

Anonymous (Tue, 03/01/2016 - 08:10)

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

Anonymous (Mon, 03/13/2017 - 19:59)

Permalink

I am writing a drawing program for school but need to add the stop() function but can't figure out how to define and use it.

  1. from turtle import *
  2.  
  3. speed(10)
  4.  
  5. # These two variables call two turtles.
  6. turtle_1 = Turtle()
  7. turtle_2 = Turtle()
  8.  
  9. def callback_1(x,y):
  10. color("black")
  11. shape("turtle")
  12.  
  13. def callback_2(x,y):
  14. color("brown")
  15. shape("triangle")
  16. circle(100, steps=3)
  17.  
  18. # These two lines of code choose color of turtles.
  19. turtle_1.color("black")
  20. turtle_2.color("brown")
  21.  
  22. # These two lines of code choose shape of turtles.
  23. turtle_1.shape("turtle")
  24. turtle_2.shape("triangle")
  25.  
  26. # This function makes turtle_1 draw a square.
  27. def draw_square_1():
  28. turtle_1.setheading(270)
  29. turtle_1.circle(100,steps=4)
  30.  
  31. # This function makes turtle_2 draw a hexagon.
  32. def draw_hexagon_2():
  33. turtle_2.setheading(90)
  34. turtle_2.circle(150,steps=6)
  35.  
  36. # This function moves turtle_2 to a new location.
  37. def move_turtle_2():
  38. turtle_2.penup()
  39. turtle_2.goto(-200,200)
  40. turtle_2.pendown()
  41.  
  42. # This function defines turtles location after reset.
  43. def place_turtles():
  44. turtle_1.color("black")
  45. turtle_1.shape("turtle")
  46. turtle_1.penup()
  47. turtle_1.goto(0,0)
  48. turtle_1.pendown()
  49. turtle_2.color("brown")
  50. turtle_2.shape("triangle")
  51. turtle_2.penup()
  52. turtle_2.goto(0,0)
  53. turtle_2.pendown()
  54.  
  55. # This function resets screen.
  56. def start_over():
  57. resetscreen()
  58. place_turtles()
  59.  
  60. def stop():
  61. stop()
  62.  
  63. listen()
  64.  
  65. # The functions below moves the turtles or draws a shape when certain keys are pressed.
  66. onkey(draw_square_1, "s")
  67. onkey(move_turtle_2,"m")
  68. onkey(draw_hexagon_2, "h")
  69. onkey(bye,"Escape")
  70. onkey(start_over,"space")
  71. onkey(stop,"Home")
  72.  
  73. place_turtles()

 

Josiah (Fri, 10/13/2017 - 16:05)

Permalink

Above given syntax are useful.but i have an error

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

 

priyanka (Mon, 03/19/2018 - 06:06)

Permalink
add the last line mainloop()

Ash (Mon, 04/23/2018 - 16:43)

Permalink

I am trying to make a chode your ending game but when they die it continues with the game. How do I make specific parts of my game stop when the player chooses a action and they die?

example

river = raw_input(“oh no there is a river what do we do?”)

print “you decide”

print(“1.go through the river”)

print(“1.swing on a vine over the river”)

answer = input()

if (answer==1):

       print “you safely made it across”

if (answer==2):

       print “you died when the vine broke”

 

how do I break answer 2 without stopping answer 1?

Zylina Sala (Tue, 07/17/2018 - 22:15)

Permalink

Zylina Sala

import sys

if (answer == 2):

    print("You died when the vine broke")

    sys.exit()

Ezekiel Koenig (Wed, 10/17/2018 - 19:58)

Permalink

i'm trying to get it to 'spit it out' when i say

sys.exit("[Error]THIS HAS NOT BEEN PROGRAMMED!")

but it just exits and doesn't say that...

please reply

 

P.S. Ignore the website. i didn't know what to put.

edward green (Tue, 02/19/2019 - 17:52)

Permalink

Reading the python docs, you might be intercepting the exception that sys.exit() raises, which is then suppressing the error. Maybe?

Also, you don't have to put a website in, it's purely optional.

philipnorton42 (Tue, 02/19/2019 - 21:03)

Permalink

print ("Guess any number between 1 and 20. You have 5 lives.")
from random import *
Memory = randint(1,20)
for i in range(5):
    Guess = int(input("What is your guess?"))

    if Guess == Memory:
        print ("Correct!")
        print ("You win!")
        break
        
    else:
        print ("Not quite.")

print ("Oops! You ran out of lives!")

^This is what I'm being taught to make (a guessing game). If the player's guess was correct, it will come up with:

Correct!

You win!

Oops! You ran out of lives!

??? How to I get the game to stop before printing "Oops! You ran out of lives!"? Can anyone help?

eva (Wed, 03/20/2019 - 21:31)

Permalink

I just read about stopping a running program from within the program using: import sys; sys.exit('program stopping')

Very cool.  When I tried this in Python 3.7 without the sys. in front of the exit, I got a window pop up asking if I really wanted to 'kill' or cancel.  What's up with that?

Thanks!

 

Treehugger Dave (Thu, 10/10/2019 - 12:40)

Add new comment

The content of this field is kept private and will not be shown publicly.