【问题标题】:Taking input while accounting for both Python 2.x and 3.x在考虑 Python 2.x 和 3.x 的同时接受输入
【发布时间】:2018-01-09 15:50:39
【问题描述】:

由于 Python 2 的 raw_input 更改为仅用于 Python 3 的 input,我想知道是否有办法在考虑 Python 2 和 3 的同时接受输入。我正在尝试为两者编写脚本版本,并且这个输入部分是唯一不能正常工作的部分。

我尝试使用 Py2 仅运行 input,结果出现了这种情况:

>>> a = input('Input: ')
inp: test
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    a = input('Input: ')
  File "<string>", line 1, in <module>
NameError: name 'test' is not defined

我看到了引用输入的解决方法:

>>> a = input('Input: ')
inp: "testing test"
a
'testing test'

有没有办法将引号连接到输入的开头和结尾? '"' + input('input: ') + '"' 不工作

【问题讨论】:

标签: python-3.x python-2.7


【解决方案1】:

可能不是一个好习惯,但您可以使用try 块来测试raw_input() 是否被识别(从而告诉您您使用的是Python 2.x 还是Python 3.x):

try:
    a = raw_input('input: ')
except NameError:
    a = input('input: ')

我会使用raw_input() 进行测试,因为它不被 Python 3.x 接受并且是您希望在 Python 2.x 中使用的,所以input() 不会在 Python 2.x 中触发。

我不是专家,所以我相信有更好的建议。

@Chris_Rands 的suggested dupe thread 通过绑定input = raw_input 有一个更优雅的解决方案,因此如果您有多个input(),您只需try 一次。

【讨论】:

  • 就像你说的,在生产中不是一个很好的方法,但对于一个小的个人丢弃脚本来说完全没问题。
  • 我自己也是一个初学者,所以什么是最佳实践对我来说仍然非常陌生。无论如何,IMO 在两个 Python 版本中都支持脚本似乎是一个奇怪的想法。就我个人而言,我会将它分成两个版本,并让另一个 main.py 检查版本以确定启动哪个脚本。
【解决方案2】:

这适用于 Python 2 和 3。

from builtins import input
input("Type something safe please: ")

【讨论】:

    猜你喜欢
    • 2013-10-02
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多