简体   繁体   English

如何在 Python 3 中使用 raw_input?

[英]How do I use raw_input in Python 3?

In Python 2:在 Python 2 中:

raw_input()

In Python 3, I get an error:在 Python 3 中,我收到一个错误:

NameError: name 'raw_input' is not defined NameError:未定义名称“raw_input”

Starting with Python 3, raw_input() was renamed to input() .从 Python 3 开始, raw_input()被重命名为input()

From What's New In Python 3.0, Builtins section second item.来自Python 3.0 中的新增功能,内置部分第二项。

This works in Python 3.x and 2.x:这适用于 Python 3.x 和 2.x:

# Fix Python 2.x.
try: input = raw_input
except NameError: pass
print("Hi " + input("Say something: "))

A reliable way to address this is解决此问题的可靠方法是

from six.moves import input

six is a module which patches over many of the 2/3 common code base pain points. 6是一个修补许多 2/3 常见代码库痛点的模块。

在Python 3.xx中,您只需要input()而不是raw_input()

As others have indicated, the raw_input function has been renamed to input in Python 3.0, and you really would be better served by a more up-to-date book, but I want to point out that there are better ways to see the output of your script.正如其他人所指出的那样, raw_input函数在 Python 3.0 中已重命名为input ,并且您确实会得到一本更新的书更好的服务,但我想指出,有更好的方法来查看输出你的脚本。

From your description, I think you're using Windows, you've saved a .py file and then you're double-clicking on it to run it.根据您的描述,我认为您使用的是 Windows,您已经保存了一个.py文件,然后您双击它来运行它。 The terminal window that pops up closes as soon as your program ends, so you can't see what the result of your program was.程序结束后弹出的终端窗口会立即关闭,因此您看不到程序的结果。 To solve this, your book recommends adding a raw_input / input statement to wait until the user presses enter.为了解决这个问题,你的书建议添加一个raw_input / input语句来等到用户按下回车键。 However, as you've seen, if something goes wrong, such as an error in your program, that statement won't be executed and the window will close without you being able to see what went wrong.但是,正如您所看到的,如果出现问题,例如程序中的错误,该语句将不会被执行,并且窗口将关闭,而您无法看到出了什么问题。 You might find it easier to use a command-prompt or IDLE.您可能会发现使用命令提示符或 IDLE 更容易。

Use a command-prompt使用命令提示符

When you're looking at the folder window that contains your Python program, hold down shift and right-click anywhere in the white background area of the window.当您查看包含 Python 程序的文件夹窗口时,按住 shift 并右键单击窗口白色背景区域的任意位置。 The menu that pops up should contain an entry "Open command window here".弹出的菜单应包含一个条目“在此处打开命令窗口”。 (I think this works on Windows Vista and Windows 7.) This will open a command-prompt window that looks something like this: (我认为这适用于 Windows Vista 和 Windows 7。)这将打开一个命令提示符窗口,如下所示:

    Microsoft Windows [Version 6.1.7601]
    Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

    C:\Users\Weeble\My Python Program>_

To run your program, type the following (substituting your script name):要运行您的程序,请键入以下内容(替换您的脚本名称):

    python myscript.py

...and press enter. ...然后按 Enter。 (If you get an error that "python" is not a recognized command, see http://showmedo.com/videotutorials/video?name=960000&fromSeriesID=96 ) When your program finishes running, whether it completes successfully or not, the window will remain open and the command-prompt will appear again for you to type another command. (如果您收到“python”不是可识别的命令的错误,请参阅http://showmedo.com/videotutorials/video?name=960000&fromSeriesID=96 )当您的程序运行完成时,无论是否成功完成,窗口将保持打开状态,命令提示符将再次出现,供您键入另一个命令。 If you want to run your program again, you can press the up arrow to recall the previous command you entered and press enter to run it again, rather than having to type out the file name every time.如果你想再次运行你的程序,你可以按向上箭头来调用你之前输入的命令,然后按回车再次运行它,而不必每次都输入文件名。

Use IDLE使用空闲

IDLE is a simple program editor that comes installed with Python. IDLE 是一个简单的程序编辑器,随 Python 一起安装。 Among other features it can run your programs in a window.除其他功能外,它还可以在窗口中运行您的程序。 Right-click on your .py file and choose "Edit in IDLE".右键单击您的.py文件并选择“在 IDLE 中编辑”。 When your program appears in the editor, press F5 or choose "Run module" from the "Run" menu.当您的程序出现在编辑器中时,按 F5 或从“运行”菜单中选择“运行模块”。 Your program will run in a window that stays open after your program ends, and in which you can enter Python commands to run immediately.您的程序将在程序结束后保持打开的窗口中运行,您可以在其中输入 Python 命令以立即运行。

Timmerman's solution works great when running the code, but if you don't want to get Undefined name errors when using pyflakes or a similar linter you could use the following instead: Timmerman 的解决方案在运行代码时效果很好,但如果您不想在使用 pyflakes 或类似的 linter 时出现Undefined name错误,您可以使用以下代码:

try:
    import __builtin__
    input = getattr(__builtin__, 'raw_input')
except (ImportError, AttributeError):
    pass

Here's a piece of code I put in my scripts that I wan't to run in py2/3-agnostic environment:这是我放入脚本中的一段代码,我不想在与 py2/3 无关的环境中运行:

# Thank you, python2-3 team, for making such a fantastic mess with
# input/raw_input :-)
real_raw_input = vars(__builtins__).get('raw_input',input)

Now you can use real_raw_input.现在您可以使用 real_raw_input。 It's quite expensive but short and readable.它相当昂贵,但简短易读。 Using raw input is usually time expensive (waiting for input), so it's not important.使用原始输入通常很耗时(等待输入),所以它并不重要。

In theory, you can even assign raw_input instead of real_raw_input but there might be modules that check existence of raw_input and behave accordingly.理论上,您甚至可以分配 raw_input 而不是 real_raw_input,但可能会有模块检查 raw_input 的存在并做出相应的行为。 It's better stay on the safe side.最好保持安全。

Probably not the best solution, but before I came here I just made this on the fly to keep working without having a quick break from study.可能不是最好的解决方案,但在我来这里之前,我只是在飞行中做这个以继续工作,而不会从学习中快速休息。

def raw_input(x):
  input(x)

Then when I run raw_input('Enter your first name: ') on the script I was working on, it captures it as does input() would.然后,当我在正在处理的脚本上运行raw_input('Enter your first name: ')时,它会像input()那样捕获它。

There may be a reason not to do this, that I haven't come across yet!可能有理由不这样做,我还没有遇到过!

How about the following one?下面的那一个呢? Should allow you to use either raw_input or input in both Python2 and Python3 with the semantics of Python2's raw_input (aka the semantics of Python3's input)应该允许您在 Python2 和 Python3 中使用 raw_input 或 input 以及 Python2 的 raw_input 语义(也就是 Python3 输入的语义)

# raw_input isn't defined in Python3.x, whereas input wasn't behaving like raw_input in Python 2.x
# this should make both input and raw_input work in Python 2.x/3.x like the raw_input from Python 2.x 
try: input = raw_input
except NameError: raw_input = input

another way you can do it like this, by creating a new function.通过创建一个新函数,您可以通过另一种方式做到这一点。

import platform
def str_input(str=''):
    py_version = platform.python_version() # fetch the python version currently in use
    if int(py_version[0]) == 2:
       return raw_input(str) # input string in python2
    if int(py_version[0]) == 3:
       return input(str) # input string in python3

how to use:如何使用:

str_input("Your Name: ")

I use this when I want to create scripts and inputs that can be run in python2 and python3当我想创建可以在 python2 和 python3 中运行的脚本和输入时,我会使用它

raw_input() function has been removed from Python 3.x. raw_input()函数已从Python 3.x中删除。 to take the input python2 used to have two function that were input() and raw_input() 取输入python2曾经有两个函数,分别是input()和raw_input()

If you want to have the same feature of 2.x in 3.x to take input parameter please follow this wiki link https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output 如果要在3.x中具有2.x的相同功能以获取输入参数,请遵循此Wiki链接https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM