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