Created
April 12, 2016 14:38
-
-
Save fritzvd/398a8bace17771e524d65d85c3a897ec to your computer and use it in GitHub Desktop.
Live streaming of stdout over udp with ansible // based on: http://rferrer.me/articles/live-ansible-stdout.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
# Add a custom listener to read out stdout | |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
while True: | |
rfd, wfd, efd = select.select(rpipes, [], rpipes, 1) | |
if cmd.stdout in rfd: | |
dat = os.read(cmd.stdout.fileno(), 9000) | |
stdout += dat | |
sock.sendto(dat, ("127.0.0.1", 9876)) # append to listener | |
if dat == '': | |
rpipes.remove(cmd.stdout) | |
if cmd.stderr in rfd: | |
dat = os.read(cmd.stderr.fileno(), 9000) | |
stderr += dat | |
sock.sendto(dat, ("127.0.0.1", 9876)) # append to listener | |
if dat == '': | |
rpipes.remove(cmd.stderr) | |
# if we're checking for prompts, do it now | |
if prompt_re: | |
if prompt_re.search(stdout) and not data: | |
return (257, stdout, "A prompt was encountered while running a command, but no input data was specified") | |
# 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: | |
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 | |
# NOTE: Actually cmd.poll() is always None here if rpipes is empty | |
elif not rpipes and cmd.poll() == None: | |
cmd.wait() | |
# The process is terminated. Since no pipes to read from are | |
# left, there is no need to call select() again. | |
break | |
cmd.stdout.close() | |
cmd.stderr.close() | |
# close the socket! | |
sock.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment