python中的raw_input而不按回车 [英] raw_input in python without pressing enter

查看:76
本文介绍了python中的raw_input而不按回车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 中使用 raw_input 与 shell 中的用户交互.

I'm using raw_input in Python to interact with user in shell.

c = raw_input('Press s or n to continue:')
if c.upper() == 'S':
    print 'YES'

它按预期工作,但用户必须在按 's' 后在 shell 中按 Enter.有没有办法从用户输入中完成我需要的操作,而无需在 shell 中按 Enter 键?我正在使用 *nixes 机器.

It works as intended, but the user has to press enter in the shell after pressing 's'. Is there a way to accomplish what I need from an user input without needing to press enter in the shell? I'm using *nixes machines.

推荐答案

在 Windows 下,你需要 msvcrt 模块,具体来说,从你描述问题的方式来看,函数 msvcrt.getch:

Under Windows, you need the msvcrt module, specifically, it seems from the way you describe your problem, the function msvcrt.getch:

读取按键并返回结果字符.没有回声到控制台.此调用将阻止如果还没有按键可用,但不会等待 Enter被按下.

Read a keypress and return the resulting character. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed.

(等等——参见我刚刚提到的文档).对于 Unix,请参见例如这个秘籍 一个简单的方法构建一个类似的 getch 函数(另请参阅该配方的评论线程中的几个替代方案 &c).

(etc -- see the docs I just pointed to). For Unix, see e.g. this recipe for a simple way to build a similar getch function (see also several alternatives &c in the comment thread of that recipe).

这篇关于python中的raw_input而不按回车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆