简体   繁体   中英

python-sys.stdin.readlines() ,Stop reading lines in command line

I have a code with function sys.stdin.readlines() .

  1. What is the difference between the above one and sys.stdin.buffer.readlines() ?.

  2. What exactly do they do ?

  3. If they read lines from command line,how to stop reading lines at a certain instant and proceed to flow through the program?

1) sys.stdin is a TextIOWrapper , its purpose is to read text from stdin. The resulting strings will be actual str s. sys.stdin.buffer is a BufferedReader . The lines you get from this will be byte strings

2) They read all the lines from stdin until hitting eof or they hit the limit you give them

3) If you're trying to read a single line, you can use .readline() (note: no s ). Otherwise, when interacting with the program on the command line, you'd have to give it the EOF signal (Ctrl+D on *nix)

Is there a reason you are doing this rather than just calling input() to get one text line at a time from stdin?

From the docs

sys.stdin

sys.stdout

sys.stderr

File objects corresponding to the interpreter's standard input, output and error streams. stdin is used for all interpreter input except for scripts but including calls to input(). stdout is used for the output of print() and expression statements and for the prompts of input(). The interpreter's own prompts and (almost all of) its error messages go to stderr. stdout and stderr needn't be built-in file objects: any object is acceptable as long as it has a write() method that takes a string argument. (Changing these objects doesn't affect the standard I/O streams of processes executed by os.popen(), os.system() or the exec*() family of functions in the os module.)

Note: The standard streams are in text mode by default. To write or read binary data to these, use the underlying binary buffer. For example, to write bytes to stdout, use sys.stdout.buffer.write(b'abc') .

So, sys.stdin.readlines() reads everything that was passed to stdin and separates the contents so lines are formed (you get a list as a result).

sys.stdin.buffer.readlines() does the same, but for buffer of stdin. I'd suggest to use the first method as the buffer may be empty while stdin may contain some data.

If you want to stop at some moment, then use readline() to read only one line at a time .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM