From d5324c11a0c389d2ede8375e2024cb37b9eb8ce5 Mon Sep 17 00:00:00 2001 From: Steve Kuznetsov Date: Tue, 13 Dec 2016 09:29:10 -0500 Subject: [PATCH] Factored polling std{out,err} reads into a function The process to poll for data in the stdout and/or stderr pipes during a low-level command execution was repetitive. Factoring this out into a function DRYs out the code. Signed-off-by: Steve Kuznetsov --- lib/ansible/module_utils/basic.py | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/lib/ansible/module_utils/basic.py b/lib/ansible/module_utils/basic.py index a7203e87bb9..2ad55f0e170 100644 --- a/lib/ansible/module_utils/basic.py +++ b/lib/ansible/module_utils/basic.py @@ -2133,6 +2133,15 @@ class AnsibleModule(object): else: self.fail_json(msg='Could not replace file: %s to %s: %s' % (src, dest, exception)) + def _read_from_pipes(self, rpipes, rfds, file_descriptor): + data = b('') + if file_descriptor in rfds: + data = os.read(file_descriptor.fileno(), 9000) + if data == b(''): + rpipes.remove(file_descriptor) + + return data + def run_command(self, args, check_rc=False, close_fds=True, executable=None, data=None, binary_data=False, path_prefix=None, cwd=None, use_unsafe_shell=False, prompt_regex=None, environ_update=None, umask=None, encoding='utf-8', errors='surrogate_or_strict'): ''' Execute a command, returns rc, stdout, and stderr. @@ -2329,17 +2338,9 @@ class AnsibleModule(object): cmd.stdin.close() while True: - rfd, wfd, efd = select.select(rpipes, [], rpipes, 1) - if cmd.stdout in rfd: - dat = os.read(cmd.stdout.fileno(), 9000) - stdout += dat - if dat == b(''): - rpipes.remove(cmd.stdout) - if cmd.stderr in rfd: - dat = os.read(cmd.stderr.fileno(), 9000) - stderr += dat - if dat == b(''): - rpipes.remove(cmd.stderr) + rfds, wfds, efds = select.select(rpipes, [], rpipes, 1) + stdout += self._read_from_pipes(rpipes, rfds, cmd.stdout) + stderr += self._read_from_pipes(rpipes, rfds, cmd.stderr) # if we're checking for prompts, do it now if prompt_re: if prompt_re.search(stdout) and not data: @@ -2351,7 +2352,7 @@ class AnsibleModule(object): # only break out if no pipes are left to read or # the pipes are completely read and # the process is terminated - if (not rpipes or not rfd) and cmd.poll() is not None: + if (not rpipes or not rfds) and cmd.poll() is not None: break # No pipes are left to read but process is not yet terminated # Only then it is safe to wait for the process to be finished