(embedding) running Python as coprocess

William Park opengeometry at yahoo.ca
Wed Feb 19 20:38:25 EST 2003


William Park <opengeometry at yahoo.ca> wrote:
> Jp Calderone <exarkun at intarweb.us> wrote:
>> Instead of running -just- Python, run a Python program.  It can
>> attach itself to a couple fifos (or a unix socket, or a tcp socket,
>> or ...), read until EOF, process the string (easy, with exec/eval),
>> write the results out, then re-open the input file.
> 
> Thanks Jp.  I overlooked 'exec' function in Python.
> 
> I was initially thinking about writing a C wrapper program, which will
> read the batch commands from 'stdin' (redirected from FIFO), pass it
> to PyRun_SimpleString(), and repeat.  The result will in 'stdout'
> (redirected to FIFO), and reading it would be up to the calling
> program.  
> 
> But, somehow, I ended up with full-blown embedded Python within Bash
> shell. :-)

Finally found 'exec' solution, thanks to Jp.  I've come up with the
following:

    import sys
    fifo_in = sys.argv[1]
    fifo_out = sys.argv[2]
    while 1:
	fin = open(fifo_in, "r")
	fout = open(fifo_out, "w")
	sys.stdout = fout
	exec fin
	sys.stdout.flush()
	fout.close()
	fin.close()

If this is called 'coprocess.py', then you can do

    mkfifo in out
    python coprocess.py in out &

    echo "print 1.0+2.0" > in
    cat out
    echo "import math" > in
    echo "print math.pi" > in
    cat out

-- 
William Park, Open Geometry Consulting, <opengeometry at yahoo.ca>
Linux solution for data management and processing. 




More information about the Python-list mailing list