Skip to content
Advertisement

how to keep a subprocess running and keep supplying output to it in python?

I am not able to keep alive a tunnel created by subprocess to fire multiple commands.
first i tried this to execute a subprocess

command=['gdb']
process=subprocess.Popen(command,stdout=subprocess.PIPE,stdin=subprocess.PIPE)
(out,err)=process.communicate("""file demo
b main
r
""")
print out

then i tried this

command=['gdb']
process=subprocess.Popen(command,stdout=subprocess.PIPE,stdin=subprocess.PIPE)
process.stdin.write("b main")
process.stdin.write("r")
print repr(process.stdout.readlines())
process.stdin.write("n")
print repr(process.stdout.readlines())
process.stdin.write("n")
print repr(process.stdout.readlines())
process.stdin.write("n")
print repr(process.stdout.readlines())
process.stdin.close()

in first case it executes the commands and then exits the gdb making it impossible to keep suplying commands to gdb and in second case it does not execute after b main command (i.e. gdb exits).
so how can i keep on giving more commands to gdb from the program as i require. and how to get output of the gdb after execution of each command.
command to be given to gdb are not known at the start they can only be entered by user of the python program so passing long strings in process.communicate will not help

Advertisement

Answer

As noticed, communicate() and readlines() are not fit for the task because they don’t return before gdb’s output has ended, i. e. gdb exited. We want to read gdb’s output until it waits for input; one way to do this is to read until gdb’s prompt appears – see below function get_output():

from subprocess import Popen, PIPE, STDOUT
from os         import read
command = ['gdb', 'demo']
process = Popen(command, stdin=PIPE, stdout=PIPE, stderr=STDOUT)

def get_output():
    output = ""
    while not output.endswith("n(gdb) "):  # read output till prompt
        buffer = read(process.stdout.fileno(), 4096)
        if (not buffer): break              # or till EOF (gdb exited)
        output += buffer
    return output

print get_output()
process.stdin.write("b mainn")             # don't forget the "n"!
print get_output()
process.stdin.write("rn")                  # don't forget the "n"!
print get_output()
process.stdin.write("nn")                  # don't forget the "n"!
print get_output()
process.stdin.write("nn")                  # don't forget the "n"!
print get_output()
process.stdin.write("nn")                  # don't forget the "n"!
print get_output()
process.stdin.close()
print get_output()
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement