Skip to main content
 首页 » 编程设计

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

2025年05月04日6hnrainll

我看到一些代码(例如 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: "))