Masking exceptions in Python? -


it typical use with statement open file file handle cannot leaked:

with open("myfile") f:     … 

but if exception occurs somewhere within open call? open function not atomic instruction in python interpreter, it's entirely possible asynchronous exception such keyboardinterrupt thrown* @ moment before open call has finished, after system call has completed.

the conventional way of handle (in, example, posix signals) use masking mechanism: while masked, delivery of exceptions suspended until later unmasked. allows operations such open implemented in atomic way. such primitive exist in python?


[*] 1 might it's doesn't matter keyboardinterrupt since program die anyway, not true of programs. it's conceivable program might choose catch keyboardinterrupt on top level , continue execution, in case leaked file handle can add on time.

i not think possible mask exceptions , can mask signals not exceptions . in case keyboardinterrupt exception raised when signal.sigint raised (which ctrl + c) .

it not possible mask exceptions because not make sense, right? let's doing open('file','r') , file not exist, causes open function throw ioerror exception, should not able mask these kinds of exceptions. not make sense mask it, because open never able complete in above case.

exceptions – anomalous or exceptional conditions requiring special processing

for keyboardinterrupt exception , different because said, signal causes keyboardinterrupt exception raised.

you can mask signals in unix starting python 3.3 using function signal.pthread_sigmask [reference]

for have move the context expression different block can mask signal, run context expression context manager , unmask signal , sample code (please note have not tested code) -

import signal signal.pthread_sigmask(signal.sig_block,[signal.sigint]) <context expression> variable:  # in case ,open('filename','r')      signal.pthread_sigmask(signal.sig_unblock,[signal.sigint]) ... 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -