head
reads from stdout
then closes it. This causes print
to fail, internally it writes to sys.stdout
, now closed.
You can simply catch the IOError
and exit silently:
try:
for pid, uid, pname in data:
print template.format(pid, uid, pname)
except IOError:
# stdout is closed, no point in continuing
# Attempt to close them explicitly to prevent cleanup problems:
try:
sys.stdout.close()
except IOError:
pass
try:
sys.stderr.close()
except IOError:
pass