diff --git a/lib/ansible/utils/display.py b/lib/ansible/utils/display.py index 3c0d3f7b5fc..9662b04b3dd 100644 --- a/lib/ansible/utils/display.py +++ b/lib/ansible/utils/display.py @@ -28,6 +28,7 @@ import time import locale import logging import getpass +import errno from struct import unpack, pack from termios import TIOCGWINSZ from multiprocessing import Lock @@ -129,11 +130,19 @@ class Display: msg2 = to_unicode(msg2, self._output_encoding(stderr=stderr)) if not stderr: - sys.stdout.write(msg2) - sys.stdout.flush() + fileobj = sys.stdout else: - sys.stderr.write(msg2) - sys.stderr.flush() + fileobj = sys.stderr + + fileobj.write(msg2) + + try: + fileobj.flush() + except IOError as e: + # Ignore EPIPE in case fileobj has been prematurely closed, eg. + # when piping to "head -n1" + if e.errno != errno.EPIPE: + raise if logger and not screen_only: msg2 = nocolor.lstrip(u'\n')