Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to poll a file handle returned from subprocess.Popen?

Say I write this:

from subprocessing import Popen, STDOUT, PIPE
p = Popen(["myproc"], stderr=STDOUT, stdout=PIPE)

Now if I do

line = p.stdout.readline()

my program waits until the subprocess outputs the next line.

Is there any magic I can do to p.stdout so that I could read the output if it's there, but just continue otherwise? I'm looking for something like Queue.get_nowait()

I know I can just create a thread for reading p.stdout, but let's assume I can't create new threads.

like image 203
itsadok Avatar asked Dec 13 '22 04:12

itsadok


1 Answers

Use p.stdout.read(1) this will read character by character

And here is a full example:

import subprocess
import sys

process = subprocess.Popen(
    cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)

while True:
    out = process.stdout.read(1)
    if out == '' and process.poll() != None:
        break
    if out != '':
        sys.stdout.write(out)
        sys.stdout.flush()
like image 83
Nadia Alramli Avatar answered Jan 10 '23 07:01

Nadia Alramli