Correct way to pause a Python program

Question:

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?

Asked By: RandomPhobia

||

Answers:

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")
Answered By: mhawke

I assume you want to pause without input.

Use:

time.sleep(seconds)

Answered By: 8bitwide

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

Python 3.x:

input('Press <ENTER> to continue')

Python 2.x:

raw_input('Press <ENTER> to continue')

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.

Anecdote: There was a time where programs used "press [ANY] key to continue". This failed because people were complaining they could not find the key ANY on their keyboard 🙂

Answered By: ntg

For Windows only, use:

import os
os.system("pause")
Answered By: Chan Tzish

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.

Answered By: olean

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

Answered By: Cether

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.

Answered By: mbiella

Very simple:

raw_input("Press Enter to continue ...")
print("Doing something...")
Answered By: Bu Saeed
print ("This is how you pause")

input()

Answered By: 1byanymeans

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...")
Answered By: Adewole Adesola

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.

Answered By: Alex B

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?

Answered By: Samie Bencherif

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...' )
Answered By: BuvinJ

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
Answered By: user12532854

cross-platform way; works everywhere

import os, sys

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

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
Answered By: Walter Nissen

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()
Answered By: Hoi Wong
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.