[Tutor] Wrap a pipe to get text mode

Avi Gross avigross at verizon.net
Sat Dec 1 17:02:14 EST 2018


Brief(er) message on topic:

 

Someone was having a problem that was traced to their use of a pipe to
communicate between tasks that normally passes data in binary mode.

 

They were offered solutions on how to convert the data that should work
fine. I am offering a different solution from the Lutz Book I am currently
reading:

 

Programming Python: Powerful Object-Oriented Programming

By Mark Lutz

 

This is the snippet on-line:

 

https://books.google.com/books?id=q8W3WQbNWmkC
<https://books.google.com/books?id=q8W3WQbNWmkC&pg=PA226&lpg=PA226&dq=python
+wrap+a+pipe&source=bl&ots=Y8ddhRkA2E&sig=NW2YygRxI9qUtJjMQx77Xhwfy88&hl=en&
sa=X&ved=2ahUKEwj-sZygzv_eAhUCnFkKHbbxBu8Q6AEwCnoECAQQAQ#v=onepage&q=python%
20wrap%20a%20pipe&f=false>
&pg=PA226&lpg=PA226&dq=python+wrap+a+pipe&source=bl&ots=Y8ddhRkA2E&sig=NW2Yy
gRxI9qUtJjMQx77Xhwfy88&hl=en&sa=X&ved=2ahUKEwj-sZygzv_eAhUCnFkKHbbxBu8Q6AEwC
noECAQQAQ#v=onepage&q=python%20wrap%20a%20pipe&f=false

 

The key is to take one end of the pipe and wrap a file around it that then
provides the interface that processes and returns raw data as text:

 

In the parent, take the side of the pipe you read from, called pipein as in:

 

pipe, pipeout = os.pipe

 

and do this:

 

pipein = os.fdopen(pipein)

 

NOTE that their method does not use Popen() to sun a command. Your child
process would need to start that program on their own. But the text received
would not require further processing from binary.

 

Many other solutions exist, such as on some systems using named pipes which
can be opened in text mode. Even simpler is to run the external process with
an argument like ">file" and have python open that file in text mode after
it completes. These solutions do require having permission to create files
and perhaps require additional effort to create a unique temp file.

 

 



More information about the Tutor mailing list