Correct way to pause a Python program

PythonSleep

Python Problem Overview


I've been using the input function as a way to pause my scripts:

print("something")
wait = input("Press Enter to continue.")
print("something")

Is there a formal way to do this?

Python Solutions


Solution 1 - Python

It seems fine to me (or raw_input() in Python 2.X). Alternatively, you could use time.sleep() if you want to pause for a certain number of seconds.

import time
print("something")
time.sleep(5.5)    # Pause 5.5 seconds
print("something")

Solution 2 - Python

For Windows only, use:

import os
os.system("pause")

Solution 3 - Python

So, I found this to work very well in my coding endeavors. I simply created a function at the very beginning of my program,

def pause():
    programPause = raw_input("Press the <ENTER> key to continue...")

and now I can use the pause() function whenever I need to just as if I was writing a batch file. For example, in a program such as this:

import os
import system

def pause():
    programPause = raw_input("Press the <ENTER> key to continue...")

print("Think about what you ate for dinner last night...")
pause()

Now obviously this program has no objective and is just for example purposes, but you can understand precisely what I mean.

NOTE: For Python 3, you will need to use input as opposed to raw_input

Solution 4 - Python

I assume you want to pause without input.

Use:

time.sleep(seconds)

Solution 5 - Python

I have had a similar question and I was using signal:

import signal

def signal_handler(signal_number, frame):
    print "Proceed ..."

signal.signal(signal.SIGINT, signal_handler)
signal.pause()

So you register a handler for the signal SIGINT and pause waiting for any signal. Now from outside your program (e.g. in bash), you can run kill -2 <python_pid>, which will send signal 2 (i.e. SIGINT) to your python program. Your program will call your registered handler and proceed running.

Solution 6 - Python

print ("This is how you pause")

input()

Solution 7 - Python

I use the following for Python 2 and Python 3 to pause code execution until user presses Enter

import six

if six.PY2:
    raw_input("Press the <Enter> key to continue...")
else:
    input("Press the <Enter> key to continue...")

Solution 8 - Python

As pointed out by mhawke and steveha's comments, the best answer to this exact question would be:

> For a long block of text, it is best to use input('Press <ENTER> to continue') (or raw_input('Press <ENTER> to continue') on > Python 2.x) to prompt the user, rather than a time delay. Fast readers > won't want to wait for a delay, slow readers might want more time on > the delay, someone might be interrupted while reading it and want a > lot more time, etc. Also, if someone uses the program a lot, he/she > may become used to how it works and not need to even read the long > text. It's just friendlier to let the user control how long the block > of text is displayed for reading.

Solution 9 - Python

Very simple:

raw_input("Press Enter to continue ...")
print("Doing something...")

Solution 10 - Python

By this method, you can resume your program just by pressing any specified key you've specified that:

import keyboard
while True:
    key = keyboard.read_key()
    if key == 'space':  # You can put any key you like instead of 'space'
        break

The same method, but in another way:

import keyboard
while True:
    if keyboard.is_pressed('space'):  # The same. you can put any key you like instead of 'space'
        break

Note: you can install the keyboard module simply by writing this in you shell or cmd:

pip install keyboard

Solution 11 - Python

cross-platform way; works everywhere

import os, sys

if sys.platform == 'win32':
    os.system('pause')
else:
    input('Press any key to continue...')

Solution 12 - Python

I work with non-programmers who like a simple solution:

import code
code.interact(banner='Paused. Press ^D (Ctrl+D) to continue.', local=globals()) 

This produces an interpreter that acts almost exactly like the real interpreter, including the current context, with only the output:

Paused. Press ^D (Ctrl+D) to continue.
>>>

The Python Debugger is also a good way to pause.

import pdb
pdb.set_trace() # Python 2

or

breakpoint() # Python 3

Solution 13 - Python

I think that the best way to stop the execution is the time.sleep() function.

If you need to suspend the execution only in certain cases you can simply implement an if statement like this:

if somethinghappen:
    time.sleep(seconds)

You can leave the else branch empty.

Solution 14 - Python

In Linux, you can issue kill -TSTP <pid> to the background and stop a process. So, it's there, but not consuming CPU time.

Then later, kill -CONT <pid> and it's off and running again.

Solution 15 - Python

I think I like this solution:

import getpass
getpass.getpass("Press Enter to Continue")

It hides whatever the user types in, which helps clarify that input is not used here.

But be mindful on the OS X platform. It displays a key which may be confusing.

It shows a key, like I said


Probably the best solution would be to do something similar to the getpass module yourself, without making a read -s call. Maybe making the foreground color match the background?

Solution 16 - Python

user12532854 suggested using keyboard.readkey() but the it requires specific key (I tried to run it with no input args but it ended up immediately returning 'enter' instead of waiting for the keystroke).

By phrasing the question in a different way (looking for getchar() equivalent in python), I discovered readchar.readkey() does the trick after exploring readchar package prompted by this answer.

import readchar
readchar.readkey()

Solution 17 - Python

For cross Python 2/3 compatibility, you can use input via the six library:

import six
six.moves.input( 'Press the <ENTER> key to continue...' )

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRandomPhobiaView Question on Stackoverflow
Solution 1 - PythonmhawkeView Answer on Stackoverflow
Solution 2 - PythonChan TzishView Answer on Stackoverflow
Solution 3 - PythonCetherView Answer on Stackoverflow
Solution 4 - Python8bitwideView Answer on Stackoverflow
Solution 5 - PythonoleanView Answer on Stackoverflow
Solution 6 - Python1byanymeansView Answer on Stackoverflow
Solution 7 - PythonAdewole AdesolaView Answer on Stackoverflow
Solution 8 - PythonntgView Answer on Stackoverflow
Solution 9 - PythonBu SaeedView Answer on Stackoverflow
Solution 10 - Pythonuser12532854View Answer on Stackoverflow
Solution 11 - PythonMujeeb IshaqueView Answer on Stackoverflow
Solution 12 - PythonWalter NissenView Answer on Stackoverflow
Solution 13 - PythonmbiellaView Answer on Stackoverflow
Solution 14 - PythonAlex BView Answer on Stackoverflow
Solution 15 - PythonSamie BencherifView Answer on Stackoverflow
Solution 16 - PythonHoi WongView Answer on Stackoverflow
Solution 17 - PythonBuvinJView Answer on Stackoverflow