gpt4 book ai didi

python - 我应该如何编写使用 `raw_input` 的应用程序来使用 Python 2.x 和 3.x?

转载 作者:太空宇宙 更新时间:2023-11-04 06:42:47 26 4
gpt4 key购买 nike

我看到一些代码(例如 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 的形式)如何处理?现在是怎么做到的?

最佳答案

这个怎么样?

try: 
input = raw_input
except NameError:
pass
print("Hi " + input("Say something: "))

关于python - 我应该如何编写使用 `raw_input` 的应用程序来使用 Python 2.x 和 3.x?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25390269/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com