Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python2.7 peek at stdin

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

like image 525
Erin Avatar asked Jul 17 '13 22:07

Erin


1 Answers

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.

like image 100
Dr. Jan-Philip Gehrcke Avatar answered Sep 22 '22 22:09

Dr. Jan-Philip Gehrcke