1

I am implementing a CI platform and need to run a bunch of tests in a shell script that need to be delivered and analyzed in real-time. I figured I needed to use subprocess.Popen and use .stdout.readline() to get the output upon execution. A sample of that is demonstrated below:

process = subprocess.Popen(["/bin/bash", "script.sh"], stdout=subprocess.PIPE)

while True:
    output = process.stdout.readline()
    if process.poll is not None and output == "":
        break

    if output:
        # do whatever you want with the output
        print(output.strip())
 

The above code works, however, during the course of execution, there maybe errors. I would have to use process.stderr.readline() to get the errors but I want to be able to get the errors and output as a single object (string) not separate objects (strings).

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
Kali
  • 21
  • 3

1 Answers1

2

Pass stderr=subprocess.STDOUT to Popen:

subprocess.Popen(["/bin/bash", "script.sh"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
mipadi
  • 398,885
  • 90
  • 523
  • 479
  • In [How to Answer](https://stackoverflow.com/help/how-to-answer), note the section _Answer Well-Asked Questions_, and the bullet point therein regarding questions that have been "asked and answered many times before". – Charles Duffy Jul 09 '22 at 00:25
  • @CharlesDuffy: Sorry, I don't have an encyclopedic knowledge of every question asked on SO. – mipadi Jul 09 '22 at 00:28
  • (Especially since the linked question is only tangentially the same as this one.) – mipadi Jul 09 '22 at 00:34
  • Thanks @mipadi I tried your solution and it works. – Kali Jul 09 '22 at 07:02