Search code examples
python-2.7python-3.xinputkeypressraw-input

How should I wait for a keypress in both Python 2 and Python 3?


This is probably a very simple question, but I haven't found a simple solution. In Python2, I can wait for a keypress in the following way:

raw_input("\nPress Enter to continue.")

In Python 3, I can wait for a keypress in the following way:

input("\nPress Enter to continue.")

How should I wait for a keypress in a script that is intended to be compatible with both Python 2 and Python 3?


EDIT: So, for example, is the following function about as efficient as I can get?

def pause(
    text = "\nPress Enter to continue."
    ):
    if sys.version_info[0] < 3:
        raw_input(text)
    else:
        input(text)

Solution

  • You can always do

    try:
        input = raw_input
    except NameError:
        pass
    

    So you'll always write

    input('...')
    

    And forget about the old and obsolete input on Python 2.x