python 设置按键停止脚本

2025-10-24 06:32:56

1、首先,按回车键退出。

#coding=utf-8

raw_input(unicode('按回车键退出...','utf-8').encode('gbk'))

python 设置按键停止脚本

2、按任意键继续。

import os

os.system('pause')

接下码国羞来即Linux下实现python版本的按任意键退出。

初学Python时在总想实现一个按任意键继续/退出的程序(受.bat毒害), 奈何一直写不出来, 最近学习Unix C时发现可以通过 termios.h 库来实现, 尝试一下发现Python也有这个库, 所以终于此物写出一个这样的程序. 下面是代码:#!/usr/bin/env python

# -*- coding:utf-8 -*-

import os

import sys

import termios

def press_any_key_exit(msg):

python 设置按键停止脚本

3、 # 获取标准输入的描述符牺牺

  fd = sys.stdin.fileno()

  # 获取标准输入(终端)的设置

  old_ttyinfo = termios.tcgetattr(fd)

  # 配置终端

  new_ttyinfo = old_ttyinfo[:]

  # 使用非规范模式(索引3是c_lflag 也就是本地模式)

  new_ttyinfo[3] &= ~termios.ICANON

  # 关闭回显(输入不会被显示)

  new_ttyinfo[3] &= ~termios.ECHO

  

python 设置按键停止脚本

4、# 输出信息

  sys.stdout.write(msg)

  sys.stdout.flush()

  # 使设置生效

  termios.tcsetattr(fd, termios.TCSANOW, new_ttyinfo)

  # 从终端读取

  os.read(fd, 7)

 

python 设置按键停止脚本

5、 # 还原终端设置

  termios.tcsetattr(fd, termios.TCSANOW, old_ttyinfo)

if __name__ == "__main__":

  press_any_key_exit("按任意键继续...")

  press_any_key_exit("按任意键退出...")

python 设置按键停止脚本

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢