1. 使用`input()`函数:
name = input("Enter your name: ")
print("Hello, " + name + "!")
2. 使用`raw_input()`函数(Python 2.x版本中):
name = raw_input("Enter your name: ")
print("Hello, " + name + "!")
3. 使用`getpass`模块获取密码输入:
password = getpass.getpass("Enter your password: ")
print("Your password was received.")
4. 使用`msvcrt`模块(仅限Windows系统):
import msvcrt
print("Press any key to continue...")
msvcrt.getch()
print("You pressed a key.")
5. 使用`pygame`库(用于游戏开发等):
import pygame
pygame.init()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
else:
print("You pressed the key: " + str(event.key))
6. 自定义键盘输入读取类(例如,不显示输入内容):
class _Getch:
def __init__(self):
try:
import msvcrt
except ImportError:
import sys, termios, tty
self.fd = sys.stdin.fileno()
self.old_termios = termios.tcgetattr(self.fd)
def __call__(self):
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_termios)
return ch
getch = _Getch()
print("Press any key to continue...")
key = getch()
print("You pressed the key: " + key)