1

I have a command that provides event stream - new message every few second. How do I read this as it comes with python?

The standard approach with

def getMessage(command):
    lines = os.popen(command).readlines()
    return lines

waits for the command to complete, but in this command run forever. It will continue on and print new message to stdout every few seconds. How do I pass it on to python? I want to capture all messages in the stream.

1 Answer 1

4

You can read the output line by line and process/print it. Meanwhile use p.poll to check if the process has ended.

def get_message(command):
    p = subprocess.Popen(
        command, 
        stdout=subprocess.PIPE,
    )
    while True:
        output = p.stdout.readline()
        if output == '' and p.poll() is not None:
            break
        if output:
            yield output.strip()

Sign up to request clarification or add additional context in comments.

1 Comment

I needed small modification: p = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True, universal_newlines=True) but otherwise it works great, Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.