在 Python2 中如要想要获得用户从命令行的输入,可以使用 input() 和 raw_input() 两个函数,那么这两者有什么区别呢?
我们先借助 help 函数来看下两者的文档注释:

>>> help(raw_input)
Help on built-in function raw_input in module __builtin__:

raw_input(...)
    raw_input([prompt]) -> string

    Read a string from standard input.  The trailing newline is stripped.
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
    On Unix, GNU readline is used if enabled.  The prompt string, if given,
    is printed without a trailing newline before reading.

>>> help(input)
Help on built-in function input in module __builtin__:

input(...)
    input([prompt]) -> value

    Equivalent to eval(raw_input(prompt)).

可以看出,raw_input() 返回的始终是一个“原始”(raw)字符串,并且去掉了行末的换行符。
值得注意的是,文档还提到“On Unix, GNU readline is used if enabled. ”,
这是说,如果 *nix 系统中安装了 GNU readline 库,并且在 python 中启用了(import readline),那么 raw_input() 底层就会调用这个库。
如果不启用,raw_input() 也能用,只不过会读取你键盘输入的所有字符,包括不可见字符,比如回退键……这样就很不方便了是不是。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。



而 input() 其实是在 raw_input() 返回的结果上再 调用了 eval() 函数,把原始字符串计算成 python 可以识别的对象。



在 Pyhon3 中,已经没有 raw_input() 函数了,而剩下 input() 函数与 Python2 中的 raw_input() 行为一致:

>>> help(raw_input)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'raw_input' is not defined


>>> help(input)
Help on built-in function input in module builtins:

input(prompt=None, /)
    Read a string from standard input.  The trailing newline is stripped.

    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.

    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄