Search code examples
pythonpython-3.xiosubprocessoutput

How do I wait for a subprocess to finish, store it's output and add a prefix (without a new line) to the output?


I have a Python(3) script that's calling an external command using the subprocess.call([...]) method:

import subprocess

print("Prefix: ")
subprocess.call(["cmd", "--option", "filename.x"])

The command executes without any errors but the problem is the output.

The output isn't "uniform" and sometimes the program will output:

Program output...
Prefix:

And other times the output will be:

Prefix:
Program output....

The result I'm looking for is:

Prefix: Program output...

I know that in order to achieve this result I need to wait for the subprocess to finish, store it's output and then print the prefix (without \n) with the subprocess' output after it, I just can't figure out how to do it.

Thanks.


Solution

  • First you need to import the sys module, so you can use sys.stdout's write and flush methods.

    import sys
    

    You'll also need to import the subprocess module so you can use the subprocess.check_output method.

    import subprocess
    

    Use sys.stdout.write instead of print:

    sys.stdout.write("Prefix: ")
    

    Then you'll need to replace subprocess.call with subprocess.check_output, which runs the given command and waits for the output.

    response = subprocess.check_output(["cmd", "--option", "filename.x"])
    

    NOTE: you need to decode the response because it's a bytes object and not a string.

    sys.stdout.write(response.decode("UTF-8"))
    

    And finally you need to flush the output:

    sys.stdout.flush()
    

    Here is the final result:

    import sys, subprocess
    sys.stdout.write("Prefix: ")
    response = subprocess.check_output(["cmd", "--option", "filename.x"])
    sys.stdout.write(response.decode("UTF-8"))
    sys.stdout.flush()
    

    Good luck, hopefully no one else will stumble on this question like I did.