Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中未按enter键的原始输入_Python_User Input - Fatal编程技术网

python中未按enter键的原始输入

python中未按enter键的原始输入,python,user-input,Python,User Input,我在Python中使用raw\u input与shell中的用户交互 c = raw_input('Press s or n to continue:') if c.upper() == 'S': print 'YES' 它按预期工作,但用户必须在按“s”后在shell中按enter键。有没有一种方法可以在不需要在shell中按enter键的情况下从用户输入中完成我需要的内容?我使用的是*nixes机器。在Windows下,您需要msvcrt模块,具体地说,从您描述问题的方式来看,功能

我在Python中使用
raw\u input
与shell中的用户交互

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

它按预期工作,但用户必须在按“s”后在shell中按enter键。有没有一种方法可以在不需要在shell中按enter键的情况下从用户输入中完成我需要的内容?我使用的是*nixes机器。

在Windows下,您需要
msvcrt
模块,具体地说,从您描述问题的方式来看,功能:

阅读按键并返回 结果字符。没有回声 到控制台。此呼叫将被阻止 如果还没有按键 可用,但不会等待输入 被压迫


(等等——参见我刚才提到的文档)。对于Unix,请参见,例如,有关构建类似的
getch
函数的简单方法(另请参见该配方注释线程中的几个备选方案&c)。

Python不提供现成的多平台解决方案。
如果您使用的是Windows,则可以尝试使用:


除了
msvcrt
模块,您还可以使用:


另一方面,msvcrt.kbhit()返回一个布尔值,确定当前是否按下了键盘上的任何键

因此,如果您正在制作一个游戏或其他东西,并且希望按键可以执行某些操作,但不能完全停止游戏,那么可以在if语句中使用kbhit(),以确保仅当用户确实想要执行某项操作时才检索到该键

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

为了得到一个字符,我使用了,但我不知道它是否在Windows上工作。

诅咒也可以这样做:


我知道这很古老,但解决方案对我来说还不够好。 我需要支持跨平台和的解决方案,而无需安装任何外部Python包

我的解决方案,以防其他人看到这篇文章

参考:

从tkinter导入Tk,帧
定义设置键(e,根):
"""
e-属性为“char”的事件,释放的密钥
"""
按下全局键
如果e.char:
按下按键=e.char
root.destroy()
def get_键(msg=“按任意键…”,睡眠时间=3):
"""
msg-如果不想打印任何内容,请设置为空字符串
睡眠时间-默认为3秒
"""
按下全局键
如果消息:
打印(msg)
按键按下=无
root=Tk()
root.overrideredirect(True)
框架=框架(根,宽度=0,高度=0)
frame.bind(“,lambda f:uu设置_键(f,根))
frame.pack()
root.focus_set()
frame.focus_set()
frame.focus_force()#在没有它的情况下无法在while循环中工作
root.after(睡眠时间*1000,func=root.destroy)
root.mainloop()
root=无#以防万一
按下返回键
def__main():
c=无
虽然不是c:
c=获取_键(“选择你的武器…”,2)
印刷品(c)
如果名称=“\uuuuu main\uuuuuuuu”:
__main()
实际上,在这段时间内(从本线程开始的将近10年),出现了一个名为的跨平台模块。 在第一个切口下方-即仅适用于小写“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")

如果您可以使用外部库,(跨平台)可以非常轻松地做到这一点:

来自导入终端
术语=终端()
使用term.cbreak():#设置要立即读取的键
打印(“按任意键继续”)
inp=term.inkey()#等待并读取一个字符
请注意,在
with
块中时,终端的行编辑功能将被禁用


inkey的文档和带有inkey的文档

我遇到过这个模块,但我需要它在*尼克斯上工作。无论如何谢谢你!它可以按预期工作,拥有一个跨平台的解决方案是非常棒的。谢谢你的回答!直接转到,似乎可以完成大部分操作,但我无法让它正确读取OSX上的箭头键。Linux和Mac用户呢?有其他选择吗?请参阅本页。它使用ttyl模块,只有两行。只需省略ord()命令:
# 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
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))
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()
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")