Python2.7 peek at stdin

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

For example, I want:

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

then x and y have the same lines. It would be acceptable if I could read from stdin and add content again.

Background:

I have a module in which EITER takes one file as input and the argument is optional OR “any input connected to the module” and “argument argument”

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

It works for me, and it works great. I check sys.stdin.isatty() to determine if there is any input channel. If there is, the module throws an error if there is more than one argument from the command line (there may be one argument - an optional argument, but files are not specified if there is stdin)

The reason I am having a problem is because I need unit tests to pass on the command line as well as in eclipse. Everything works fine on the command line, but it looks like the sys.stdin plugin for eclipse also uses sys.stdin .

If I call sys.stdin.readlines() , then eclipse refuses to run unit tests. In addition, eclipse pushes things towards sys.stdin even when I do not specify any arguments, which makes it difficult to determine if the arguments are valid 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 it. Any answer that solves this problem would be satisfactory.

Possible Duplicate: Look into the Popen pipeline thread in Python

Thanks!

Edit: no luck with something like ...

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

Edit: Removed restoring stdin in tearDown and putting it in a test function, but the effect

+6
source share
1 answer

When you read the tube, the data is no longer in the tube. You can use the polling mechanism to see if there is any data to read at all, but you cannot watch content without deleting the content, at least not on Linux.

I would simply ignore stdin if the file is provided (e.g. check the file argument first), and if the file was not provided as an argument, check stdin.

+1
source

Source: https://habr.com/ru/post/949689/


All Articles