If you are familiar with Bash scripting you probably knows what trap is and does. If not, here is a quick summary of it:
“trap signals and other events.
Defines and activates handlers to be run when the shell receives signals
or other conditions“
If you read or type Bash script you already either was trap on it or added some to handle within a specific situation. These days I’m translating a bash code into python and found it, so decided to implement a trap that handles with that specific situation. Bash code was something like:
trap "rm -rf $tmp" 0 1 2 3 4 5 6 7 8 10 11 12 13 14 15
Situation is basically you create a temporary directory and want to have it delete in case a signal happens. The way Bash does is basically signal handling, so to do it in Python is quite easy.
import os
import signal
import tempfile
def trap(tmpdir):
# the handler func
def remove_dir(signum, stack):
os.rmdir(tmpdir)
signals = []
for n, i in enumerate(signal.Signals):
# 1 to 15 signal except sgkill (9)
if int(i) != 9:
signals.append(i)
if n+1 == 15:
break
# if any of these signals is triggered
# calls the handler func.
for i in signals:
signal.signal(i, remove_dir)
# testing ...
if __name__ == "__main__":
# creates a tempdif into current . dir
tmpdir = tempfile.mkdtemp('','','.')
trap(tmpdir)
while True:
pass
That is it! 🙂 thanks for reading!