Skip to content
Advertisement

python: find in subprocess’s output, leave it running and continue

I was have to call a shell command

subprocess.Popen(command, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)

I did it. and:

and, that command is prints lots of things like verbose is on, and then when its done it’s job it prints (writes) blah blah : Ready

I have to call this command, wait for the ‘Ready’ text and leave it running on background, then let the rest of the code run

I tried this and things like this, didn’t work

...
done=False
with subprocess.Popen(command, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) as proc:
  while not done:
    x=proc.stdout.read()
    x=x.find('Ready')
    if x > -1:
      done=True
  print("YaaaY, this subprocess is done it's job and now running on background")
  #rest of the code

i ran similar (edited) code on python terminal and I think I can’t even access (read) the terminal of the subprocess. because… console stuck waiting

I was expecting it will show every line that this subprocess print but. its just waiting.

Advertisement

Answer

Your problem is proc.stdout.read(). This reads the entire output of your subprocess, which is not known until it has terminated (usually). Try something like:

output = b''
while not done:
  output += proc.stdout.read(1)
  x = output.find(b'Ready')
  if x > -1:
    done = True

This reads the process’s stdout one character at a time, so it doesn’t have to wait for it to finish.

Note that using Popen in a context manager (with block) will cause your program to wait for the child process to terminate before it exits the with block, so it will not leave it running past that point. It’s unclear if that is desired behaviour or not.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement