28

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 ?

Grigor Gevorgyan
  • 6,753
  • 4
  • 35
  • 64

2 Answers2

38

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.

Abhijeet
  • 8,561
  • 5
  • 70
  • 76
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • 15
    Also, `sys.stdin.readline()` can be used to read data passed to the program through a pipe like `program | my_app.py` (that's the only thing i use `sys.stdin` for in fact), which cannot be done with `raw_input()`. For me, `sys.stdin` is meant to read data passed from a pipe, and `raw_input()` for prompting for data during the program execution. – mdeous Aug 06 '11 at 11:05
  • 2
    This not seems to be true for me. In Python 2.7 `raw_input()` reads the first line from the pipe, not all of them although. – kissgyorgy May 12 '15 at 17:02
  • Doesn't "I *personally prefer* using raw_input() to fetch user input, and readline() to read lines out of a file" contradicts "they're not really interchangeable" as it shows just a matter of preference rather than real feature separation?! – Niccolò Feb 29 '16 at 11:12
  • 1
    @Niccolò, my point was that, while it is theoretically possible to use `readline()` to fetch user input, I avoid doing that myself. I have listed the differences between the two functions in my first two paragraphs. – Frédéric Hamidi Feb 29 '16 at 11:16
  • URLs broken (redirecting to v3 doc). Correct ones are https://docs.python.org/2/library/functions.html#raw_input and https://docs.python.org/2/library/stdtypes.html#file.readline – calandoa Feb 02 '17 at 15:30
8

"However, from the point of view of many Python beginners and educators, the use of sys.stdin.readline() presents the following problems:

  1. Compared to the name "raw_input", the name "sys.stdin.readline()" is clunky and inelegant.

  2. 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/

Mariy
  • 5,746
  • 4
  • 40
  • 57