Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does sys.exit() not exit when called inside a thread in Python?

This could be a stupid question, but I'm testing out some of my assumptions about Python and I'm confused as to why the following code snippet would not exit when called in the thread, but would exit when called in the main thread.

import sys, time from threading import Thread  def testexit():     time.sleep(5)     sys.exit()     print "post thread exit"  t = Thread(target = testexit) t.start() t.join() print "pre main exit, post thread exit" sys.exit() print "post main exit" 

The docs for sys.exit() state that the call should exit from Python. I can see from the output of this program that "post thread exit" is never printed, but the main thread just keeps on going even after the thread calls exit.

Is a separate instance of the interpreter being created for each thread, and the call to exit() is just exiting that separate instance? If so, how does the threading implementation manage access to shared resources? What if I did want to exit the program from the thread (not that I actually want to, but just so I understand)?

like image 763
Shabbyrobe Avatar asked May 25 '09 03:05

Shabbyrobe


People also ask

What does sys exit do in Python?

exit() function allows the developer to exit from Python. The exit function takes an optional argument, typically an integer, that gives an exit status. Zero is considered a “successful termination”.

Is it good to use Sys exit in Python?

sys.exit([arg]) Unlike quit() and exit() , sys. exit() is considered good to be used in production code for the sys module is always available. The optional argument arg can be an integer giving the exit or another type of object. If it is an integer, zero is considered “successful termination”.

What is the difference between exit () and SYS exit ()?

exit is a helper for the interactive shell - sys. exit is intended for use in programs. The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace (e.g. exit ).


1 Answers

sys.exit() raises the SystemExit exception, as does thread.exit(). So, when sys.exit() raises that exception inside that thread, it has the same effect as calling thread.exit(), which is why only the thread exits.

like image 155
rpkelly Avatar answered Oct 05 '22 12:10

rpkelly