2

在 2.6 中,如果我需要接受允许百分号的输入(例如“foo % bar”),我会使用raw_input()which 按预期工作。

在 3.0 中,input()完成相同的操作(raw_input() 已离开建筑物)。

作为一个练习,我希望我可以有一个向后兼容的版本,它可以与 2.6 和 3.0 一起使用。

当我在 2.6 中使用 input() 并输入“foo % bar”时,返回以下错误:

  File "<string>", line 1, in <module>
NameError: name "foo" is not defined

...这是预期的。

无论如何要完成接受包含在 2.6 和 3.0 中都可以使用的百分号的输入?

谢谢。

4

2 回答 2

2

您可以使用sys.version_info它来检测正在运行的 Python 版本。

import sys
if sys.version_info[0] == 2:
    input = raw_input
# Now you can use
input()

或者,如果您不想覆盖 Python 2.X 的内置input函数,您可以编写

import sys
if sys.version_info[0] == 2:
    my_input = raw_input
else:
    my_input = input
# Now you can use
my_input()

虽然,即使在我的第一个代码示例中,原始内置input始终可以作为__builtins__.input.

于 2010-06-17T03:17:03.217 回答
2

虽然不是一个优雅(而且相当丑陋)的解决方案,但我会做这样的事情:

try:
    input = raw_input
except:
    pass
于 2010-06-17T03:18:30.060 回答