python 设置按键停止脚本

 时间:2026-02-13 01:55:38

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 设置按键停止脚本

  • win10磁盘配额怎么设置 如何为用户分配磁盘空间
  • 解决WMIC中普通用户远程管理时拒绝访问错误
  • 虚拟机怎么修改硬盘大小
  • Win10设置账户密码方法
  • 用DOS怎么查看用户账号
  • 热门搜索
    借贷记账法的特点 小孩受凉呕吐怎么办 奥格瑞玛怎么去外域 巴西旅游 惠州商贸旅游高级职业技术学校 旅游网站设计 脸部痤疮怎么办 怎么查找ip地址 社保可以退吗 长白山景区