[Pythonmac-SIG] Reading from an External Buffer

Jack Jansen Jack.Jansen@oratrix.com
Sun, 23 Mar 2003 21:39:41 +0100


On zondag, maa 23, 2003, at 07:35 Europe/Amsterdam, Bill Orcutt wrote:

> Hi-
>
> I'm working on a Macintosh C program that embeds some python code. I'm
> using "PyMac_SetConsoleHandler" to suppress the SIOUX console, and
> I've created my own write handler that captures Python's stdout &
> stderr and redirects them into my C code. So far no problem.
>
> Now I'd like to do the same for stdin, reading lines from a buffer in
> my C code and passing them to sys.stdin in my Python code when
> sys.stdin.readline() is called. Unfortunately, the only thing I've 
> found
> that works so far is to write the data to temp file in C and then read 
> it
> out from Python. But that's a not much of solution, is it?

If all the data for stdin is available before you start the Python code 
then the easiest
is to put it into a python string object, and put a StringIO wrapper 
around that (this
is an object that has a file-like API but reads data from a string 
buffer or writes
it to a string buffer).

If the data isn't all available at python script startup then you could 
write a C
extension module that simulates as much of a file object as you need 
and calls your code
to get data. But I think that if you're going down this route then 
there's something
wrong with your design (unless you need the "read from stdin" behavior 
because of
cross-platform requirements or some such).
--
- Jack Jansen        <Jack.Jansen@oratrix.com>        
http://www.cwi.nl/~jack -
- If I can't dance I don't want to be part of your revolution -- Emma 
Goldman -