0

I was looking in google lot of example, but none work, I print to a file that passes through an outlet pipe ms-dos, but this throws me an error as if my file could not read sys.stdin, I put the code:

import sys
line = sys.stdin
for l in line.read():
   print l

and ms-dos I write the following:

ping 127.0.0.1 | pipetest.py

console above shows me that I have mistake in the line of "for" and shows this:

IOError: [Errno 9] Bad file descriptor

I use python2.7, and windows.

Francisco
  • 539
  • 2
  • 8
  • 25

3 Answers3

1

This works:

import sys
lines = sys.stdin
for l in lines:
   print l

You might run into buffering issues though, because of how Python iterates on files. If you want to read each line right away, you should use readline() instead:

import sys
lines = sys.stdin
for l in iter(lines.readline, ''):
    print l
remram
  • 4,805
  • 1
  • 29
  • 42
  • 1
    it doesn't fix `"Bad file descriptor"` error. btw, you could use `for line in iter(sys.stdin.readline, ''): print line,` instead of the `while` loop. – jfs Nov 06 '13 at 20:22
  • Edited, thanks. I'm not getting "bad file descriptor" here on Windows 7, not sure what would do that. – remram Nov 06 '13 at 21:54
1

Instead of

ping 127.0.0.1 | pipetest.py

try

ping 127.0.0.1 | python pipetest.py

Also consider the other suggestion, you probably don't need .read()

Andris
  • 921
  • 7
  • 14
  • [Python piping on Windows: Why does this not work?](http://stackoverflow.com/q/466801/4279) indicates that it might fix `EOFError` but OP has different `IOError(EBADF)` error. – jfs Nov 06 '13 at 20:27
  • @J.F. Sebastian Windows 7 + Python 2.7.3 gives me exactly the same `IOError: [Errno 9] Bad file descriptor` error what the OP had. The problem you linked really results in an `EOFError`. – Andris Nov 07 '13 at 12:49
  • yes, I was incorrect. [*Both* `EOFError` and `IOError(errno 9)` errors are possible](https://mail.python.org/pipermail/python-bugs-list/2004-August/024923.html) (the link is from [the accepted answer to the question I've linked](http://stackoverflow.com/a/466849/4279)) so it might provide a solution for this case too). – jfs Nov 07 '13 at 14:18
0

code correct: ping 127.0.0.1 | python pipetest.py

thank Andris

Francisco
  • 539
  • 2
  • 8
  • 25