I would like to catch all the inputs and output of a commandline program (namely, GDB, but currently changed to ls
or cat
for simplicity) and redirect it into a file, for later analysis.
I couldn't get anything close to working, but I can't understand what's wrong. Here is my last attempt:
#!/usr/bin/env python2
import subprocess
import sys
import select
import os
def get_pipe():
fd_r, fd_w = os.pipe()
return os.fdopen(fd_r, "r"), os.fdopen(fd_w, "w")
out_r, out_w = get_pipe()
err_r, err_w = get_pipe()
in_r, in_w = get_pipe()
proc = subprocess.Popen(["ls"] + sys.argv[1:], stdin=in_r, stdout=out_w, stderr=err_w)
out_w.close()
err_w.close()
in_r.close()
running = True
while running:
input_lst, output_lst, x_lst = select.select([sys.stdin],[out_r, err_r], [], 0.5)
if out_r in output_lst+input_lst:
data = out_r.readlines()
print "*",data,"*"
if err_r in output_lst+input_lst:
data = err_r.readlines()
print "+",data,"+"
if sys.stdin in input_lst:
data = sys.stdin.readline()
print "-", data, "-"
in_w.write(data)
# don't try to quit if we received some data
if len(input_lst+output_lst+x_lst) != 0:
continue
retcode = proc.poll()
if retcode is not None:
running = False
out_r.close()
err_r.close()
in_w.close
exit(retcode)
I tried several other options, like - writing a file wrapper, which was supposed to write to an external file everything written into stdin / read from stdout-err - named pipes - ...
but the best I obtained was the very first lines of "ls".
Moreover, GDB relies on readline
for CLI edition, and I feel like it won't be that easy to catch transparently!