python中的raw_input而不按回车
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3523174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
raw_input in python without pressing enter
提问by Somebody still uses you MS-DOS
I'm using raw_inputin Python to interact with user in shell.
我raw_input在 Python 中使用与 shell 中的用户进行交互。
c = raw_input('Press s or n to continue:')
if c.upper() == 'S':
print 'YES'
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.
它按预期工作,但用户必须在按 's' 后在 shell 中按 Enter。有没有办法从用户输入中完成我需要的操作,而无需在 shell 中按 Enter 键?我正在使用 *nixes 机器。
采纳答案by Alex Martelli
Under Windows, you need the msvcrtmodule, specifically, it seems from the way you describe your problem, the function msvcrt.getch:
在 Windows 下,您需要该msvcrt模块,具体来说,从您描述问题的方式来看,函数msvcrt.getch 似乎:
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.
读取按键并返回结果字符。控制台没有回显任何内容。如果按键不可用,此调用将阻塞,但不会等待按下 Enter。
(etc -- see the docs I just pointed to). For Unix, see e.g. this recipefor a simple way to build a similar getchfunction (see also several alternatives &c in the comment thread of that recipe).
(等等 - 请参阅我刚刚指出的文档)。对于 Unix,请参阅例如此配方,以了解构建类似getch函数的简单方法(另请参阅该配方的注释线程中的几个替代方法 &c)。
回答by systempuntoout
回答by John Howard
回答by Nytra
On a side note, msvcrt.kbhit() returns a boolean value determining if any key on the keyboard is currently being pressed.
附带说明一下, msvcrt.kbhit() 返回一个布尔值,确定当前是否正在按下键盘上的任何键。
So if you're making a game or something and want keypresses to do things but not halt the game entirely, you can use kbhit() inside an if statement to make sure that the key is only retrieved if the user actually wants to do something.
因此,如果您正在制作游戏或其他东西并希望按键操作但不完全停止游戏,您可以在 if 语句中使用 kbhit() 以确保仅当用户确实想要做某事时才检索密钥.
An example in Python 3:
Python 3 中的一个例子:
# this would be in some kind of check_input function
if msvcrt.kbhit():
key = msvcrt.getch().decode("utf-8").lower() # getch() returns bytes data that we need to decode in order to read properly. i also forced lowercase which is optional but recommended
if key == "w": # here 'w' is used as an example
# do stuff
elif key == "a":
# do other stuff
elif key == "j":
# you get the point
回答by Derek Kurth
回答by user2660966
curses can do that as well :
诅咒也可以做到这一点:
import curses, time def input_char(message): try: win = curses.initscr() win.addstr(0, 0, message) while True: ch = win.getch() if ch in range(32, 127): break time.sleep(0.05) finally: curses.endwin() return chr(ch) c = input_char('Do you want to continue? y/[n]') if c.lower() in ['y', 'yes']: print('yes') else: print('no (got {})'.format(c))
import curses, time def input_char(message): try: win = curses.initscr() win.addstr(0, 0, message) while True: ch = win.getch() if ch in range(32, 127): break time.sleep(0.05) finally: curses.endwin() return chr(ch) c = input_char('Do you want to continue? y/[n]') if c.lower() in ['y', 'yes']: print('yes') else: print('no (got {})'.format(c))
回答by Meir Gabay
I know this is old, but the solution wasn't good enough for me. I need the solution to support cross-platformand without installing any external Python packages.
我知道这很旧,但解决方案对我来说还不够好。我需要支持跨平台且无需安装任何外部 Python 包的解决方案。
My solution for this, in case anyone else comes across this post
我对此的解决方案,以防其他人遇到这篇文章
Reference: https://github.com/unfor19/mg-tools/blob/master/mgtools/get_key_pressed.py
参考:https: //github.com/unfor19/mg-tools/blob/master/mgtools/get_key_pressed.py
from tkinter import Tk, Frame
def __set_key(e, root):
"""
e - event with attribute 'char', the released key
"""
global key_pressed
if e.char:
key_pressed = e.char
root.destroy()
def get_key(msg="Press any key ...", time_to_sleep=3):
"""
msg - set to empty string if you don't want to print anything
time_to_sleep - default 3 seconds
"""
global key_pressed
if msg:
print(msg)
key_pressed = None
root = Tk()
root.overrideredirect(True)
frame = Frame(root, width=0, height=0)
frame.bind("<KeyRelease>", lambda f: __set_key(f, root))
frame.pack()
root.focus_set()
frame.focus_set()
frame.focus_force() # doesn't work in a while loop without it
root.after(time_to_sleep * 1000, func=root.destroy)
root.mainloop()
root = None # just in case
return key_pressed
def __main():
c = None
while not c:
c = get_key("Choose your weapon ... ", 2)
print(c)
if __name__ == "__main__":
__main()
回答by Adrian Rosoga
Actually in the meantime (almost 10 years from the start of this thread) a cross-platform module named pynputappeared. Below a first cut - i.e. that works with lowercase 's' only. I have tested it on Windows but I am almost 100% positive that it should work on Linux.
实际上在此期间(距本主题开始将近 10 年)出现了一个名为pynput的跨平台模块。在第一次剪辑下方 - 即仅适用于小写的 's'。我已经在 Windows 上测试过它,但我几乎 100% 肯定它应该可以在 Linux 上运行。
from pynput import keyboard
print('Press s or n to continue:')
with keyboard.Events() as events:
# Block for as much as possible
event = events.get(1e6)
if event.key == keyboard.KeyCode.from_char('s'):
print("YES")

