Pair of filenos read/write each other?

Antoine Pitrou solipsis at pitrou.net
Wed Aug 14 04:34:36 EDT 2013


Nobody <nobody <at> nowhere.com> writes:
> 
> On Tue, 13 Aug 2013 16:10:41 -0700, Jack Bates wrote:
> 
> > Is there anything like os.pipe() where you can read/write both ends?
> 
> There's socket.socketpair(), but it's only available on Unix.
> 
> Windows doesn't have AF_UNIX sockets, and anonymous pipes (like the ones
> created by os.pipe()) aren't bidirectional.

I'm not sure I understand the problem: you can just create two pair of pipes
using os.pipe().
If that's too low-level, you can wrap the fds using BufferedRWPair:
http://docs.python.org/3.3/library/io.html#io.BufferedRWPair

(actual incantation would be:
 r1, w1 = os.pipe()
 r2, w2 = os.pipe()

 end1 = io.BufferedRWPair(io.FileIO(r1, 'r'), io.FileIO(w2, 'w'))
 end2 = io.BufferedRWPair(io.FileIO(r2, 'r'), io.FileIO(w1, 'w'))

 end1.write(b"foo")
 end1.flush()
 end2.read(3)  # -> return b"foo"
)

An alternative is to use multiprocessing.Pipe():
http://docs.python.org/3.3/library/multiprocessing.html#multiprocessing.Pipe

In any case, Python doesn't lack facilities for doing what you want.

Regards

Antoine.





More information about the Python-list mailing list