gpt4 book ai didi

Python键绑定(bind)/捕获

转载 作者:行者123 更新时间:2023-12-01 10:52:09 30 4
gpt4 key购买 nike

我想知道在python中绑定(bind)键的最简单方法

例如,默认的 python 控制台窗口出现并等待,然后在 psuedo ->

if key "Y" is pressed:
print ("Yes")
if key "N" is pressed:
print ("No")

我想实现这个 没有 使用任何 模块 不包含在 python 中。只是纯 python

非常感谢任何和所有帮助

python 2.7 或 3.x Windows 7

注: raw_input()要求用户按回车键,因此不是键绑定(bind)

最佳答案

来自 http://code.activestate.com/recipes/134892/ (虽然有点简化):

class _Getch:
"""Gets a single character from standard input. Does not echo to the
screen."""
def __init__(self):
self.impl = _GetchUnix()
def __call__(self):
return self.impl()


class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch

getch = _Getch()

然后你可以这样做:
>>> getch()
'Y' # Here I typed Y

这很棒,因为它不需要任何 3rd 方模块。

关于Python键绑定(bind)/捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17807693/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com