理解 try and except with __builtin__

Understanding try and except with __builtin__

Python 的新手,尚未使用或接触过 __builtin__,对以下代码的实际作用感到好奇:

import sys

try:
    import __builtin__
    input = getattr(__builtin__, 'raw_input')
except (ImportError, AttributeError):
    pass

username = input("username: ")
password = input("password: ")

此代码是否用于基本检查脚本是否 运行 与 Python 2 或 Python 3,如果是 Python 2,input() 转换为 raw_input()

如果 raw_input() 存在的话,这是使 input() 引用 raw_input() 的相当糟糕的代码。这使得它与 Python 2 和 Python 3 兼容。一个更简单的方法是这样的:

try:
    input = raw_input
except NameError:
    pass

username = input("username: ")
password = input("password: ")

__builtin__ module is the module where all the builtin objects like input() and raw_input() live. But we don't need it in this case. In Python 3.x, this is called builtins,也就是为什么这段代码的作者在抓ImportError.

如果您通常需要做这种事情,最好使用six而不是手动编写所有这些东西。