Help need with subprocess communicate

Daniel Klein danielk at featherbrain.net
Wed Jun 4 02:42:04 CEST 2008


On Tue, 3 Jun 2008 14:04:10 -0700 (PDT), rdabane at gmail.com wrote:

>I'm trying to perform following type of operation from inside a python
>script.
>1. Open an application shell (basically a tcl )
>2. Run some commands on that shell and get outputs from each command
>3. Close the shell
>
>I could do it using communicate if I concatenate all my commands
>( separated by newline ) and read all the output in the end. So
>basically I could do following sequence:
>1. command1 \n command2 \n command 3 \n
>2. Read all the output
>
>But I want to perform it interactively.
>1. command1
>2. read output
>3. command2
>4. read output ......
>
>Following is my code:
>
>from subprocess import *
>p2 = Popen('qdl_tcl',stdin=PIPE,stdout=PIPE)
>o,e = p2.communicate(input='qdl_help \n qdl_read  \n
>qdl_reg_group_list ')
>
>Please suggest a way to perform it interactively with killing the
>process each time I want to communicate with it.

Use
	stdin.write(command + '\n')
to 'send' data to the sub-process.

Use
	stdout.readline()
to 'receive' data from the sub-process.

But to use this requires you open the subprocess with:

	universal_newlines = True

It assumes that 'command' will be sent with '\n' and received data will come
in a line at a time. Your Python program needs to know what to expect; you
are in control.

Alternatively, you can use std.write() and stdout.read() (without
universal_newlines) but this means you need to create your own IPC protocol
(like netstrings).

Hope this helps,

Daniel Klein



More information about the Python-list mailing list