【发布时间】:2014-08-19 18:15:13
【问题描述】:
我看到一些代码(例如this tutorial from dropbox)可能需要在 Python 2.X 上运行相当长时间,但也可能在 Python 3.X 上运行
那些项目应该如何处理raw_input?
我觉得有点像
#!/usr/bin/env python
def input_string(question=""):
"""A function that works for both, Python 2.x and Python 3.x.
It asks the user for input and returns it as a string.
"""
import sys
if sys.version_info[0] == 2:
return raw_input(question)
else:
return input(question)
# Example
answer = input_string("What is your name? ")
print(answer)
可能是个好方法,但我不太确定。
是否有“官方”建议(例如以 PEP 的形式)如何处理? 现在是怎么做到的?
【问题讨论】:
-
另外,请注意此处的建议:stackoverflow.com/a/5868543/716118。一种替代方法是简单地在 Python 2.x 中编写您的应用程序,然后使用
2to3进行转换。 -
2to3 确实将源代码从 2.x Python 代码更改为 3.x Python 代码。如果我错了,请纠正我,但生成的代码将不再适用于 Python 2.x。那不是我想要的。我想要同时适用于 Python 2 和 Python 3 的代码。
-
您希望相同的脚本在 2.x 和 3.x 中都可以工作吗?
标签: python python-2.7 python-3.x project-management