contextlib.contextmanager and try/finally
Tim Delaney
timothy.c.delaney at gmail.com
Tue Jan 31 20:45:17 EST 2012
On 1 February 2012 09:02, Peter Otten <__peter__ at web.de> wrote:
> Prasad, Ramit wrote:
> > Is that true even in the face of something like sys.exit()?
> > What happens if 1) sys.exit is called while in the same thread
> > 2) sys.exit is called from another thread but while this thread
> > is in context manager?
>
> sys.exit() uses the normal exception mechanism to terminate a program:
>
> >>> import sys
> >>> try:
> ... sys.exit()
> ... except SystemExit:
> ... print "I'd rather not"
> ...
> I'd rather not
> >>>
>
> It won't derail a context manager:
>
> >>> from contextlib import contextmanager
> >>> @contextmanager
> ... def f():
> ... try:
> ... yield
> ... finally: print "bye"
> ...
> >>> import sys
> >>> with f():
> ... sys.exit()
> ...
> bye
> $
Note OTOH that os._exit() just terminates the process with no cleanup (this
may be what you were thinking of):
>>> from contextlib import contextmanager
>>> @contextmanager
... def f():
... try:
... yield
... finally: print "bye"
...
>>> import os
>>> with f():
... os._exit(1)
...
$
Tim Delaney
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120201/75b5aea8/attachment-0001.html>
More information about the Python-list
mailing list