What (if any) are the differences between the following two methods of reading a line from standard input: raw_input()
and sys.stdin.readline()
? And in which cases one of these methods is preferable over the other ?
The input() function reads a line from the input (usually from the user), converts the line into a string by removing the trailing newline, and returns it. If EOF is read, it raises an EOFError exception.
The easiest way to obtain user input from the command-line is with the raw_input() built-in function. It reads from standard input and assigns the string value to the variable you designate. You can use the int() built-in function (Python versions older than 1.5 will have to use the string.
Standard input – This is the file-handle that a user program reads to get information from the user. We give input to the standard input (stdin). Standard output – The user program writes normal information to this file-handle. The output is returned via the Standard output (stdout).
The sys. stdin is another way is to read from the standard input the calls input() function internally. Python has another module named fileinput for reading the standard input. The input() function of this module can be used to read standard input or read content from one or more files.
raw_input() takes an optional prompt
argument. It also strips the trailing newline character from the string it returns, and supports history features if the readline module is loaded.
readline() takes an optional size
argument, does not strip the trailing newline character and does not support history whatsoever.
Since they don't do the same thing, they're not really interchangeable. I personally prefer using raw_input()
to fetch user input, and readline()
to read lines out of a file.
"However, from the point of view of many Python beginners and educators, the use of sys.stdin.readline() presents the following problems:
Compared to the name "raw_input", the name "sys.stdin.readline()" is clunky and inelegant.
The names "sys" and "stdin" have no meaning for most beginners, who are mainly interested in what the function does, and not where in the package structure it is located. The lack of meaning also makes it difficult to remember: is it "sys.stdin.readline()", or " stdin.sys.readline()"? To a programming novice, there is not any obvious reason to prefer one over the other. In contrast, functions simple and direct names like print, input, and raw_input, and open are easier to remember." from here: http://www.python.org/dev/peps/pep-3111/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With