Sunday, November 17, 2024
Google search engine
HomeLanguagesMake Python Wait For a Pressed Key

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

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:

Example:

Now the code, upon execution, halts the execution of the program and waits for the Enter keypress. If any other key is pressed, the input function stores it. Only upon the Enter keypress does the function return with the inputted data. If any other key is pressed, such as an alphabet, number, symbol, etc., the function won’t return. The next method of halting the program execution takes care of this drawback.

Python3




# The argument to the function may be any descriptive text
input("Press the Enter key to continue: ")


Output:

How to make a python script wait for a pressed key?

 

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:

How to make a python script wait for a pressed key?

 

RELATED ARTICLES

Most Popular

Recent Comments