转自 原作者Linux公社
Windows 下:
#coding=utf-8 raw_input(unicode('按回车键退出...','utf-8').encode('gbk'))
import os os.system('pause') #按任意键继续
Linux/Mac OS 下:
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import os 4 import sys 5 import termios 6 7 def press_any_key_exit(msg): 8 # 获取标准输入的描述符 9 fd = sys.stdin.fileno() 10 11 # 获取标准输入(终端)的设置 12 old_ttyinfo = termios.tcgetattr(fd) 13 14 # 配置终端 15 new_ttyinfo = old_ttyinfo[:] 16 17 # 使用非规范模式(索引3是c_lflag 也就是本地模式) 18 new_ttyinfo[3] &= ~termios.ICANON 19 # 关闭回显(输入不会被显示) 20 new_ttyinfo[3] &= ~termios.ECHO 21 22 # 输出信息 23 sys.stdout.write(msg) 24 sys.stdout.flush() 25 # 使设置生效 26 termios.tcsetattr(fd, termios.TCSANOW, new_ttyinfo) 27 # 从终端读取 28 os.read(fd, 7) 29 30 # 还原终端设置 31 termios.tcsetattr(fd, termios.TCSANOW, old_ttyinfo) 32 33 if __name__ == "__main__": 34 press_any_key_exit("按任意键继续...") 35 press_any_key_exit("按任意键退出...")