Newbie question about sending and receiving data to the command prompt.

Gabriel Genellina gagsl-py2 at
Sun Aug 24 13:49:37 CEST 2008

En Fri, 22 Aug 2008 18:25:49 -0300, n00m <n00m at> escribió:

> Is it possible to communicate in loop fashion?
> ====================================
> import subprocess as s
> proc = s.Popen('cmd.exe', stdin=s.PIPE, stdout=s.PIPE)
> while 1:
>     cmd = raw_input('cmd:')
>     res = proc.communicate(cmd + '\n')[0]
>     print res
> ====================================

Don't use communicate, it waits for the process to finish.
But you can write and read from the pipes. The hard part is to recognize *where* output from the previous command ends (so you don't read further). The code below uses #\n as the prompt:

import subprocess as s

def read_output(stdout):
  while 1:
    line = stdout.readline()
    if not line: break
    line = line.rstrip('\r\n')
    if line=='#': break
    yield line

proc = s.Popen('cmd.exe /k prompt #$_', stdin=s.PIPE, stdout=s.PIPE)
for line in read_output(proc.stdout): pass # skip over initial prompt
while 1:
  cmd = raw_input('cmd:')
  for line in read_output(proc.stdout):
    print line

Gabriel Genellina

More information about the Python-list mailing list