What does sys.stdin read?
Asked Answered
M

6

36

I get how to open files, and then use Python's pre built in functions with them. But how does sys.stdin work?

for something in sys.stdin:
    some stuff here

lines = sys.stdin.readlines()

What's the difference between the above two different uses on sys.stdin? Where is it reading the information from? Is it via keyboard, or do we still have to provide a file?

Malley answered 5/4, 2015 at 5:20 Comment(1)
Are you familiar with input()? Wherever input() would take input from, that's sys.stdin. That may be a terminal, or it may be directed from a file, or it might be coming from another program's output, or it might be something else, depending on how you invoked the program.Necklace
N
45

So you have used Python's "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 don't 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:

myprog.py < 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).

Nicole answered 5/4, 2015 at 8:37 Comment(1)
In python 3, a text stream.Nicole
R
8

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

create a simple python script, let's name it "readStdin.py":

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

Now open console any type in:

echo "line1 line2 line3" | python readStdin.py

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.

Recti answered 2/12, 2018 at 20:32 Comment(0)
S
7

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))
Swell answered 5/4, 2015 at 5:23 Comment(1)
So how is the standard input read differently when I use sys.stdin.readlines() instead of sys.stdin Does the second one reach each word? I'm still confused.Malley
P
4

According to me sys.stdin.read() method accepts a line as the input from the user until a special character like Enter Key and followed by Ctrl + D and then stores the input as the string.

Control + D works as the stop signal.

Example:

import sys

input = sys.stdin.read()
print(input)
tokens = input.split()
a = int(tokens[0])
b = int(tokens[1])
print(a + b)

After running the program enter two numbers delimited by space and after finishing press Control + D once or twice and you will be presented by the sum of the two inputs.

Pentapody answered 14/12, 2018 at 5:20 Comment(1)
After finishing with text input, press Enter and then Ctrl+Z --> on WindowsLlanes
R
3
for something in sys.stdin:
    some stuff here

The code above does not work as you expect because sys.stdin is a file handle - it is a file handle to the stdin. It will not reach the some stuff here line

lines = sys.stdin.readlines()

When the script above is run in an interactive shell, it will block the execution until a user presses Ctrl-D, which indicates the end of the input.

Rebba answered 5/4, 2015 at 5:28 Comment(1)
So how is the standard input read differently when I use sys.stdin.readlines() instead of sys.stdin Does the second one reach each word? I'm still confused.Malley
P
1

It will read the source file line by line. It is widely used in Online Judge System.

For example: suppose we have only one number 2 will be used in the file.

import sys

if __name__ == "__main__":
    n = int(sys.stdin.readline().strip())

Read the file line by line means read the number 2 (only one line in this case). Using the strip to remove unneeded space or other specified characters. This will result in n = (integer) 2.

If we have a file with two lines like:

1
2

Then, sys.stdin.readline().strip() will transform it to one line (a list, named n) with two elements 1, 2. Then we cannot use int transformer now but we can use int(n[0]) and int(n[1]) instead.

Petrol answered 10/11, 2021 at 1:17 Comment(1)
I don't understand what you mean by "will transform it to one line (a list, named n" .readline() returns a string and .strip() leaves it as a string, did you mean .split() or possibly just stdin.readlines()?Balloon

© 2022 - 2024 — McMap. All rights reserved.