Reading pipes in Python

  • Thread starter Jeroen van der Ham
  • Start date
J

Jeroen van der Ham

Hello,

During my exploration of Python and rewriting something from Perl to
Python I ran into something odd. I want to use a pipe so that a log of
a program goes into a Python script instead of a log file.

In Perl you just open a file, but specify that it is actually a pipe,
but you read from it the same way.
So I thought I'd do that with the following Python code:

f=open('/tmp/myfifo','r')
while 1:
print f.readline()

Now, here's the weird thing:
- On Darwin this seems to work okay (seen it work odd on netmounts
tho, but not able to test that atm)
- On Linux this works fine until you send something to the pipe, after
which it prints it and starts printing blank lines over and over.

Even when using os.mkfifo() to create the pipe, this still does not
work properly on Linux.
Anyone any idea why this isn't working and what can be done to make it
work?

Regards, Jeroen.
 
R

Rene Pijlman

Jeroen van der Ham:
f=open('/tmp/myfifo','r')
while 1:
print f.readline()

This loop is endless, so don't complain to us that it doesn't end :)
what can be done to make it work?

f=open('ff','r')
while 1:
li = f.readline()
if not li: break
print li,
 
B

Bryan

Rene said:
Jeroen van der Ham:



This loop is endless, so don't complain to us that it doesn't end :)




f=open('ff','r')
while 1:
li = f.readline()
if not li: break
print li,

wouldn't this work too?

for line in file('/tmp/myfifo'):
print line
 
J

Jeroen van der Ham

This loop is endless, so don't complain to us that it doesn't end :)


f=open('ff','r')
while 1:
li = f.readline()
if not li: break
print li,

This works, but only for a single line.

The idea is that the pipe takes the place of a log of an application
so that the script can do something because something is written to
the log.

Jeroen.
 
R

Rene Pijlman

Jeroen van der Ham:
Rene Pijlman:

This works, but only for a single line.

No, it works for multiple lines as well.

What you probably mean is: it works only for a single writer process. This
is what Linus said about it in 1993: "That's how a fifo is supposed to
work as far as I can tell: when all writers have exited, the reader gets
an EOF and also exits.."
http://groups.google.com/[email protected]

Try 'cat' instead of a Python script and you'll see exactly the same
behaviour.
 
S

Steve

How do we open a pipe programatically? I'm interested in redirecting
output from a program to a pipe and then using it from a python script.
Thanks

Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,277
Latest member
VytoKetoReview

Latest Threads

Top