Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

python - What does sys.stdin read?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...