python – What does sys.stdin read?

python – What does sys.stdin read?

So you have used Pythons pre built in functions, presumably like this:

file_object = open(filename)
for something in file_object:
    some stuff here

This reads the file by invoking an iterator on the file object which happens to return the next line from the file.

You could instead use:

file_object = open(filename)
lines = file_object.readlines()

which reads the lines from the current file position into a list.

Now, sys.stdin is just another file object, which happens to be opened by Python before your program starts. What you do with that file object is up to you, but it is not really any different to any other file object, its just that you dont need an open.

for something in sys.stdin:
    some stuff here

will iterate through standard input until end-of-file is reached. And so will this:

lines = sys.stdin.readlines()

Your first question is really about different ways of using a file object.

Second, where is it reading from? It is reading from file descriptor 0 (zero). On Windows it is file handle 0 (zero). File descriptor/handle 0 is connected to the console or tty by default, so in effect it is reading from the keyboard. However it can be redirected, often by a shell (like bash or cmd.exe) using syntax like this: < input_file.txt 

That alters file descriptor zero to read a file instead of the keyboard. On UNIX or Linux this uses the underlying call dup2(). Read your shell documentation for more information about redirection (or maybe man dup2 if you are brave).

It is reading from the standard input – and it should be provided by the keyboard in the form of stream data.

It is not required to provide a file, however you can use redirection to use a file as standard input.

In Python, the readlines() method reads the entire stream, and then splits it up at the newline character and creates a list of each line.

lines = sys.stdin.readlines()

The above creates a list called lines, where each element will be a line (as determined by the end of line character).

You can read more about this at the input and output section of the Python tutorial.

If you want to prompt the user for input, use the input() method (in Python 2, use raw_input()):

user_input = input(Please enter something: )
print(You entered: {}.format(user_input))

python – What does sys.stdin read?

To get a grasp how sys.stdin works do following:

create a simple python script, lets name it

import sys
lines = sys.stdin.readlines()
print (lines)

Now open console any type in:

echo line1 line2 line3 | python

The script outputs:

[line1 line2 line3 n]

So, the script has read the input into list (named lines), including the new line character produced by echo. That is.

Leave a Reply

Your email address will not be published. Required fields are marked *