Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does sys.stdin read?

Tags:

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?

like image 544
Vimzy Avatar asked Apr 05 '15 05:04

Vimzy


1 Answers

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

like image 109
cdarke Avatar answered Sep 20 '22 13:09

cdarke