Wait for a Pressed Key using the System Function

The system function inside the os library invokes the operating system’s command interpreter for the execution of commands. Most operating systems are equipped with a command that halts the execution and makes the script wait for user input. The such command for Windows Operating System is:

pause

It Suspends processing of a batch program and displays the message

Press any key to continue . . .

The command, upon execution, stops the execution of the current thread and waits for a keypress. The keypress can be any key other than a modifier key (Ctrl, Shift, Alt, etc.). The following command, when integrated into a Python program, would be as follows:

Example:

The code invokes the command processor (cmd.exe) of Windows and executes the command pause on it. The command displays a text altering the user to press a key. Upon pressing any key, the execution resumes, and the program ends. 

Python3




import os
  
# Invoking the command processor and calling the pause command
os.system('pause')


Output:

 


Make Python Wait For a Pressed Key

Halting the execution until the occurrence of an event is a very common requirement in prompt-based programs. In earlier times, the presence of functions such as getch in C/C++ was almost necessary for the code to make the console stay up to display the output. Now such shortcomings of the compiler have been dealt with, and now such functions serve a specific purpose and are utilized for a specific use case. In this article, we will learn how to make a Python script wait for a pressed key. The methods that will be discussed are as follows:

  • Using input function
  • Using system function

Similar Reads

Wait for a Pressed Key using the Input Function

This method is native and does not require the presence of any external or standard library. The input function presenting the standard Python distribution could serve the purpose. But the function is only limited to the Enter key, i.e., It requires the Enter key to be pressed for it to return. The following example demonstrates the working:...

Wait for a Pressed Key using the System Function

...