Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically stop execution of python script? [duplicate]

Tags:

python

Is it possible to stop execution of a python script at any line with a command?

Like

some code  quit() # quit at this point  some more code (that's not executed) 
like image 694
Joan Venge Avatar asked Feb 12 '09 21:02

Joan Venge


People also ask

How do you stop a Python script execution?

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 from running. It is the most reliable, cross-platform way of stopping code execution.

How do I stop a Python program after a certain time?

terminate() function will terminate foo function. p. join() is used to continue execution of main thread. If you run the above script, it will run for 10 seconds and terminate after that.

How do you exit a Python program gracefully?

Graceful exit You can use the bash command echo $? to get the exit code of the Python interpreter.

How do you exit Python code without error?

The exit function is a useful function when we want to exit from our program without the interpreter reaching the end of the program. Some of the functions used are python exit function, quit(), sys. exit(), os. _exit().


2 Answers

sys.exit() will do exactly what you want.

import sys sys.exit("Error message") 
like image 154
Moses Schwartz Avatar answered Sep 20 '22 11:09

Moses Schwartz


You could raise SystemExit(0) instead of going to all the trouble to import sys; sys.exit(0).

like image 43
joeforker Avatar answered Sep 18 '22 11:09

joeforker