Listing 9. Removing Temporary Files
#! /usr/local/bin/python
import os
import tempfile
import sys
import signal
t_path = ''
t_file = None
def cleanup(signal, frame):
if t_path != '' and t_file != None:
print 'Cleaning up temporary files ...'
os.close(t_file)
os.remove(t_path)
print 'Done!'
sys.exit(0)
else:
sys.exit(0)
signal.signal(signal.SIGHUP, cleanup)
signal.signal(signal.SIGINT, cleanup)
signal.signal(signal.SIGQUIT, cleanup)
signal.signal(signal.SIGTERM, cleanup)
try:
t_path = tempfile.mktemp()
t_file = os.open(t_path, os.O_CREAT | os.O_RDWR)
except IOError:
print 'Error: Couldn\'t create temp file.'
sys.exit(0)
#
# always close and remove the temp file
# before you exit from script
cleanup(t_path, t_file)
Copyright © 1994 - 2018 Linux Journal. All rights reserved.