'subprocess and/or Popen doesn't seem to wait for command to complete [duplicate]

I'm issuing the following commands to extract symbol information from an elf file:

p = subprocess.Popen(["gdb", "-q", "my.elf", "-ex", symbol, "-ex", "q"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

output = p.stdout.peek().decode('utf-8').splitlines()

If I run the code then the only thing I get back from the command is: 'Reading symbols from /home/user/my.elf...done.'

If I step through the code with a debugger or put in a time.sleep(1) call between the Popen and the peek() commands, then I get a list with the structure elements as members. So it looks like Popen doesn't wait for gdb to finish processing the command.

Can someone explain why this is the case and offer a workaround? Putting in a 1 second sleep between each call is going to take way too long for something that contains hundreds if not thousands of symbols. Thanks.



Solution 1:[1]

It's non-blocking - you get back a stream you can keep reading from. Why? Because that's what it's supposed to do ... it's a good way to exchange data between a parent process and a long-running child process.

If you want a blocking one-shot invocation, it's easier to use subprocess.run() rather than raw Popen.

Solution 2:[2]

Add .communicate() for waiting like this :

p = subprocess.Popen(["gdb", "-q", "my.elf", "-ex", symbol, "-ex", "q"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.communicate()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 solidpixel
Solution 2