我希望脚本等待用户按下任何键。

我怎么做?


#1楼

如果要查看他们是否按下了确切的键(例如说“ b”),请执行以下操作:

while True:choice = raw_input("> ")if choice == 'b' :print "You win"input("yay")break

#2楼

在Python 3中,不存在raw_input() 。 因此,只需使用:

input("Press Enter to continue...")

在Python 2中,您应该使用raw_input() ,因为input(prompt)等效于eval(raw_input(prompt))

raw_input("Press Enter to continue...")

但是,这仅等待用户按Enter键,因此您可能要使用msvcrt ((仅适用于Windows / DOS)使用msvcrt模块可以访问Microsoft Visual C / C ++运行时库(MSVCRT)中的许多功能):

import msvcrt as m
def wait():m.getch()

这应该等待按键。


#3楼

如果可以,请根据系统命令使用以下命令:

Linux:

os.system('read -s -n 1 -p "Press any key to continue..."')
print

视窗:

os.system("pause")

#4楼

os.system似乎总是调用sh,后者无法识别s和n选项以进行读取。 但是,可以将read命令传递给bash:

 os.system("""bash -c 'read -s -n 1 -p "Press any key to continue..."'""")

#5楼

只需使用

input("Press Enter to continue...")

解析时将导致SyntaxError:预期的EOF。

简单修复方法:

try:input("Press enter to continue")
except SyntaxError:pass

#6楼

跨平台,Python 2/3代码:

# import sys, osdef wait_key():''' Wait for a key press on the console and return it. '''result = Noneif os.name == 'nt':import msvcrtresult = msvcrt.getch()else:import termiosfd = sys.stdin.fileno()oldterm = termios.tcgetattr(fd)newattr = termios.tcgetattr(fd)newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHOtermios.tcsetattr(fd, termios.TCSANOW, newattr)try:result = sys.stdin.read(1)except IOError:passfinally:termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)return result

我删除了fctl / non-blocking东西,因为它提供了IOError ,我不需要它。 我之所以使用此代码,是因为我想阻止它。 ;)


#7楼

我是python的新手,我已经认为自己太愚蠢了,无法重现这里提出的最简单的建议。 事实证明,有一个陷阱应该知道:

当从IDLE执行python脚本时,某些IO命令的行为似乎完全不同(因为实际上没有终端窗口)。

例如。 msvcrt.getch是非阻塞的,并且始终返回$ ff。 这早在很早以前就已有报道(参见例如https://bugs.python.org/issue9290)-它被标记为已修复,在当前版本的python / IDLE中问题似乎仍然存在。

因此,如果上面发布的任何代码都不适合您,请尝试手动运行脚本,而不要从IDLE运行


#8楼

python 手册提供以下内容:

import termios, fcntl, sys, os
fd = sys.stdin.fileno()oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)try:while 1:try:c = sys.stdin.read(1)print "Got character", repr(c)except IOError: pass
finally:termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

可以合并到您的用例中。


#9楼

如果您要等待输入(因此用户敲击键盘不会引起意外情况),请使用

sys.stdin.readline()

#10楼

我不知道这样做是与平台无关的,但是在Windows下,如果使用msvcrt模块,则可以使用其getch函数:

import msvcrt
c = msvcrt.getch()
print 'you entered', c

mscvcrt还包括非阻塞kbhit()函数,以查看是否在不等待键的情况下按下了键(不确定是否有相应的curses函数)。 在UNIX下,有curses程序包,但是不确定是否可以不将其用于所有屏幕输出而使用它。 该代码在UNIX下工作:

import curses
stdscr = curses.initscr()
c = stdscr.getch()
print 'you entered', chr(c)
curses.endwin()

请注意,curses.getch()返回所按下键的序数,以便使其具有与强制转换相同的输出。


#11楼

在我的Linux机器上,我使用以下代码。 这类似于我在其他地方看到的代码(例如,在旧的python FAQ中),但是该代码在一个紧密的循环中旋转,其中该代码不起作用,并且在很多奇怪的情况下,代码无法解决这个问题代码。

def read_single_keypress():"""Waits for a single keypress on stdin.This is a silly function to call if you need to do it a lot because it hasto store stdin's current setup, setup stdin for reading single keystrokesthen read the single keystroke then revert stdin back after reading thekeystroke.Returns a tuple of characters of the key that was pressed - on Linux, pressing keys like up arrow results in a sequence of characters. Returns ('\x03',) on KeyboardInterrupt which can happen when a signal getshandled."""import termios, fcntl, sys, osfd = sys.stdin.fileno()# save old stateflags_save = fcntl.fcntl(fd, fcntl.F_GETFL)attrs_save = termios.tcgetattr(fd)# make raw - the way to do this comes from the termios(3) man page.attrs = list(attrs_save) # copy the stored version to update# iflagattrs[0] &= ~(termios.IGNBRK | termios.BRKINT | termios.PARMRK| termios.ISTRIP | termios.INLCR | termios. IGNCR| termios.ICRNL | termios.IXON )# oflagattrs[1] &= ~termios.OPOST# cflagattrs[2] &= ~(termios.CSIZE | termios. PARENB)attrs[2] |= termios.CS8# lflagattrs[3] &= ~(termios.ECHONL | termios.ECHO | termios.ICANON| termios.ISIG | termios.IEXTEN)termios.tcsetattr(fd, termios.TCSANOW, attrs)# turn off non-blockingfcntl.fcntl(fd, fcntl.F_SETFL, flags_save & ~os.O_NONBLOCK)# read a single keystrokeret = []try:ret.append(sys.stdin.read(1)) # returns a single characterfcntl.fcntl(fd, fcntl.F_SETFL, flags_save | os.O_NONBLOCK)c = sys.stdin.read(1) # returns a single characterwhile len(c) > 0:ret.append(c)c = sys.stdin.read(1)except KeyboardInterrupt:ret.append('\x03')finally:# restore old statetermios.tcsetattr(fd, termios.TCSAFLUSH, attrs_save)fcntl.fcntl(fd, fcntl.F_SETFL, flags_save)return tuple(ret)

#12楼

在Python 2中执行此操作的一种方法是使用raw_input()

raw_input("Press Enter to continue...")

在python3中,它只是input()

如何使python等待按键相关推荐

  1. python waitkey(0)_opencv学习之等待按键事件-waitKey函数

    文章来源: 序 waitKey函数属于opencv函数里既常用又非常基础的函数,无论是刚开始学习opencv,还是使用opencv进行开发调试,都可以看到waitKey函数的身影.然而最基础的东西可能 ...

  2. python模拟按键_python 模拟按键放在模拟器Python初学者的17个技巧

    Python初学者的17个技巧,有需要的朋友可以参考下. W WW.002pc .COM认为此文章对<python 模拟按键放在模拟器Python初学者的17个技巧>说的很在理. 交换变量 ...

  3. python怎么后退_使python迭代器向后退?

    无论如何,要使python列表迭代器向后移动? 基本上我有这个 class IterTest(object): def __init__(self, data): self.data = data s ...

  4. boost的chrono模块等待按键的测试程序

    boost的chrono模块等待按键的测试程序 实现功能 C++实现代码 实现功能 boost的chrono模块等待按键的测试程序 C++实现代码 #define _CRT_SECURE_NO_WAR ...

  5. 一个信道的数据传输速率为4kb/s,单向传播时延为30ms,如果使停止-等待协议的信道最大利用率达到80%,那么要求的数据帧长度至少为( )

    一个信道的数据传输速率为4kb/s,单向传播时延为30ms,如果使停止-等待协议的信道最大利用率达到80%,那么要求的数据帧长度至少为( 960bit ) 信道利用率:指发送方在一个发送周期的时间内, ...

  6. python字典按键值排序_在Python中按键或值按升序和降序对字典排序

    python字典按键值排序 Problem Statement: Write a Python program to sort (ascending and descending) a diction ...

  7. python等待用户输入_Python等待时间,等待用户输入

    python等待用户输入 Sometimes we want our python program to wait for a specific time before executing the n ...

  8. Python 实现按键精灵的功能,超简单详细(Windows版)

    Python 实现按键精灵的功能,超简单详细 前言: 实现步骤 一.安装三个库 二.试运行简单的功能 三.根据需求自己写代码 注明 前言: 最近公司的同事让我帮他点点点,懒得亲自点,便在网上查找了相关 ...

  9. python 游戏按键精灵 PyDirectInput介绍

    前言: 在python关于按键精灵得操作中常用的有PyAutoGUI,但在使用的过程中,针对一些游戏就直接失灵了,特别是一些以DirectX来开发的游戏或软件.我通过收索相关资料了解到之所以会这样,是 ...

最新文章

  1. pandas使用pct_change函数计算数据列的百分比变化:计算当前元素和前一个元素之间的百分比变化(包含NaN值的情况以及数据填充方法)
  2. boost::fusion::result_of::as_vector用法的测试程序
  3. php面向对象项目,PHP的面向对象编程:开发大型PHP项目的方法(一)
  4. 减肥瘦不下来的原因找到了
  5. html5里面em是什么单位,HTML5中单位em的理解
  6. 数据仓库ETL(二)基本概念
  7. 启动Tomcat服务时,出现org.apache.catalina.startup.VersionLoggerListener报错
  8. 2021年度中国商业地产100强揭晓,排名前十位变化不大
  9. eyoucms留言模版验证码实现
  10. C语言程序出现malloc(): corrupted top size异常中止
  11. 结合百度搜索引擎SEO优化指南揭密百度SEO建议
  12. 第三部分 数据结构 -第一章 栈-1357:车厢调度(train)
  13. 电脑配件 - 机械键盘的由来, 与普通键盘的区别以及如何选购及使用维护 - 学习/实践
  14. 高颜值,类似Fliqlo的翻页时钟-BdTab组件
  15. 我打不了字计算机应用怎么办,键盘正常为什么打不了字 电脑键盘失灵怎么解决...
  16. 思科vrrp实例_Cisco 交换机 vrrp+mstp 配置实例
  17. STM32+Zigbee的使用
  18. 怎么看SaaS企业中的收入留存率?
  19. CentOS 7从零部署WCP免费开源知识管理系统(未完结,部署wcp配置修改没完成,有大佬救我一波嘛???)
  20. C语言中最难啃的硬骨头非这三个莫属

热门文章

  1. 自己动手实现OpenGL-OpenGL原来如此简单(二)
  2. 算法-----最大子序和(Java 版本)
  3. LayoutInflater.Factory 妙用
  4. 网易游戏2016实习生招聘笔试题目--井字棋
  5. saber仿真软件_电力电子应用技术的MATLAB仿真
  6. python分别统计男女人数_python实现爬虫统计学校BBS男女比例(一)
  7. swift_026(Swift 的类型转换)
  8. Android相关面试题---初识
  9. JAVA常用基础知识点[继承,抽象,接口,静态,枚举,反射,泛型,多线程...]
  10. (03) spring Boot 的配置