Python实现无需回车的“按任意键继续”功能技术问询
Hey there! The problem with using input() here is that it waits for a newline (the Enter key) to confirm input—hence why you have to press Enter after your initial key press. To get that seamless "press any key to proceed" behavior, you'll need to use platform-specific tools since Python's standard library doesn't include a cross-platform function for this out of the box. Here are your options:
1. Windows Systems
Use the built-in msvcrt module, which has a getch() function that reads a single character immediately without requiring Enter:
import msvcrt TimeLoop = False print("Press any button to start ") start_timer = msvcrt.getch() # Reads one key press right away # Optional: Decode the bytes object to a string if you need to check the specific key # start_timer = msvcrt.getch().decode('utf-8') # Your original condition always sets TimeLoop to True, so keeping that intact TimeLoop = True while TimeLoop: # Add your loop logic here print("Loop is running...") # Example: Press 'q' to exit the loop if msvcrt.getch().decode('utf-8').lower() == 'q': TimeLoop = False
2. Linux/macOS Systems
For Unix-like systems, use the termios and sys modules to temporarily adjust terminal settings, allowing single-key input:
import sys import termios import tty def get_single_key(): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) key = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return key TimeLoop = False print("Press any button to start ") start_timer = get_single_key() TimeLoop = True while TimeLoop: print("Loop is running...") # Example: Press 'q' to exit the loop if get_single_key().lower() == 'q': TimeLoop = False
3. Cross-Platform Option (Third-Party Library)
If you want a one-size-fits-all solution without writing platform-specific code, install the getch library via pip:
pip install getch
Then use it like this:
from getch import getch TimeLoop = False print("Press any button to start ") start_timer = getch() TimeLoop = True while TimeLoop: print("Loop is running...") # Example: Press 'q' to exit the loop if getch().lower() == 'q': TimeLoop = False
Quick note on your original code: The condition if start_timer != 3: TimeLoop = True else: TimeLoop = True will always set TimeLoop to True no matter what input you get—you might want to tweak that logic if you intended different behavior based on the key pressed!
内容的提问来源于stack exchange,提问作者Murg

