DEV Community


Posted on

Python: implementing a basic "press to continue"

It's a common usage to write Python scripts that can be either interrupted or re-executed:

Press Enter to continue...

Here, we'll see very basic way to implement that feature.

The goal

We want to press "enter," so the script can re-execute itself, but we also want to interrupt the script without receiving ugly errors, as interrupt is not necessarily an error here.

The code

import sys

def main():
    i = input('Press Enter to continue...')
    if i == '':

if __name__ == '__main__':
    except KeyboardInterrupt:
Enter fullscreen mode Exit fullscreen mode

The above Python script defines a function that calls itself after executing only if the user press enter without entering any input.

The try/except catches KeyboardInterrupt errors to make the terminal more friendly, as users will likely interrupt our script frequently.

Pros & cons

It only takes a few lines to write such script in Python without any third-party package.

While the approach is convenient and easy to understand, if the user inputs any char before pressing "enter," the script will exit.

You may want to modify that rule for a specific letter or word, but "Press Enter to continue..." is kind of a convention.

Top comments (0)