python2.7 peek at stdin
Asked Answered
D

1

7

I would like to call sys.stdin.readlines() without removing anything from stdin. I am using Python2.7 on Linux.

For example, what I want is:

x = sys.stdin.readlines()
y = sys.stdin.readlines()

then x and y have identical strings. It would be acceptable if I could read from stdin and put the contents back in.

Background:

I have a module that EITHER takes one file as input and an -optional argument OR "some input piped into the module" and an -optional argument

mymodule.py myfile -option
or
echo "some input" | mymodule.py -option

I have this working, and it works fine. I am checking sys.stdin.isatty() to determine if there is any input piped in. If there is, the module will throw an error if there is more than one argument from the command line (there can be one -optional argument, but no files specified if there is stdin)

The reason I'm having a problem is because I'm required to have unit tests pass on the command line but also in eclipse. Everything works fine on the command line, but it looks like the PyUnit plugin for eclipse uses sys.stdin also.

If I call sys.stdin.readlines(), then eclipse gives up on running unit tests. Additionally, eclipse is pushing things into sys.stdin even when I don't specify any arguments, which makes it difficult to determine whether there are valid arguments or not.

It seems to me that somehow getting sys.stdin.readlines() without changing the contents would be a solution, but I don't know how to do this. Any answer solving this problem would be satisfactory.

Possible duplicate: Peek into stream of Popen pipeline in Python

Thanks!

Edit: not having any luck with something like...

foo = sys.stdin.readlines()
sys.stdin.write(foo)

Edit: Removed restoring stdin in tearDown and putting it in test function instead, but no effect

Dollar answered 17/7, 2013 at 22:51 Comment(0)
B
1

When you read from a pipe, the data is not in the pipe anymore. You can use a polling mechanism in order to see if there is any data to read at all, but you cannot look at the contents without removing the contents, at least not on Linux.

I would just ignore stdin if a file is provided (i.e. check for the file argument first) and, if no file was provided as argument, validate stdin.

Bicuspid answered 17/7, 2013 at 23:12 Comment(1)
I'm quickly giving up on this. I was having some luck with reading from stdin, then setting sys.stdin = open('/dev/tty', 'r+'), but that doesn't work in Eclipse. I hesitate to figure out where the input's coming from, because ultimately the customers will be using the module on the command line anyway. I think the best solution is your suggestion -- check for a file first and then look at stdinDollar

© 2022 - 2024 — McMap. All rights reserved.