Passing parameters for a C program in Linux.

Petr Messner petr.messner at gmail.com
Tue Jun 30 15:59:35 CEST 2009


2009/6/30 venutaurus539 at gmail.com <venutaurus539 at gmail.com>:
...
> Can you give some more explanation about how exactly this can be
> done..

Popen object enables you to run any program in a newly-created child
process, write to its standard input and read from its standard and
error outputs.

There is an example how your test program could look like:

import subprocess

p = subprocess.Popen("./cli", stdin=subprocess.PIPE,
        stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)

result, errs = p.communicate("1\n44 33\n")

assert not errs
assert result.splitlines()[-1] == "Result is 77"


Popen objects have also attributes stdin, stdout and stderr, you can
use them if you do not want to use communicate().

Be aware that you if you call stdout.read(), it reads everything and
blocks until EOF occurrs (usually until the popen-ed program quits).
You can also use readline(), but this can also block until the
subprocess writes any line. In cases where this could be a problem (i
think this automated test programs are not that cases) polling,
nonblocking I/O or threads can be used.

I have pasted complete example (with a script simulating your "cli"
program) here: http://paste.pocoo.org/show/125944/

PM



More information about the Python-list mailing list