Skip to content

Instantly share code, notes, and snippets.

@microlinux
Last active September 19, 2021 21:45
Show Gist options
  • Save microlinux/cd7ddeff3a715d2fbea827ffca2b4e76 to your computer and use it in GitHub Desktop.
Save microlinux/cd7ddeff3a715d2fbea827ffca2b4e76 to your computer and use it in GitHub Desktop.
def get_command_output(timeout):
"""Reads command output from stdin and returns a list of lines.
Acks ('done' or 'error') are filtered out. Thus, commands
which produce no other output will result in an empty list.
Args:
timeout (int|float): Seconds to wait for output.
Returns:
list: Lines of output, stripped.
Raises:
CommandError: If the command errored out.
ResponseError: If no output was receieved before timeout.
"""
output = ''
while sys.stdin in select.select([sys.stdin], [], [], timeout)[0]:
output = output + os.read(sys.stdin.fileno(), 4096)
lines = output.splitlines()
logging.debug(lines)
if lines[-1] == 'error':
raise CommandError('Invalid command')
elif lines[-1] == 'done':
return lines[:-1]
raise ResponseError('No response received')
def run_command(command, timeout=3):
"""Runs a command and returns the output.
Args:
command (str): Command to run.
timeout (int|float): Seconds to wait for output.
Returns:
list: Lines of output, stripped.
"""
print command
sys.stdout.flush()
return get_command_output(timeout)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment