【问题标题】:Python input single character without enterPython输入单个字符而不输入
【发布时间】:2015-03-01 06:42:21
【问题描述】:

我想做的是用 Python 制作一个简单的 pi 记忆游戏。我需要的是一种从用户那里获取输入的方法,而不必在每个字符后按“输入”。听起来我需要像getch这样的东西,但我无法让它工作。我从这里得到了一个类似 getch 的函数:https://gist.github.com/chao787/2652257#file-getch-py。我真的不明白里面有什么。当我执行“x = getch.getch()”时,它会显示“AttributeError: '_Getch' object has no attribute 'getch'”。看起来 msvcrt 可以为 Windows 做到这一点,但我有一台 Mac。看起来curses也是一个有getch的东西,但它说我需要先做initscr,然后我得到错误“File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/curses/__init__.py", line 30, in initscr fd=_sys.__stdout__.fileno()) _curses.error: setupterm: could not find terminal”。

这是我仅使用输入的文件,您每次都必须按 Enter 键(我实际上输入了 1000 位数字,而不是省略号)。

pi = '3.1415926535...'


def main():
    print('Welcome to PiGame!')
    pigame()
    while True:
        yn = input('Play again? y/n ')
        if yn == 'y':
            pigame()
        else: return


def pigame():

    n=0

    print('Go!')


    while n<=1000:
        x = input()
        if x == pi[n]:
            n += 1
        else:
            print('I\'m sorry. The next digit was '+pi[n]+'.')
            print('You got to '+str(n)+' digits!')
            return
    print('You got to 1000! Hooray!')

【问题讨论】:

  • 是的,我读过那个。这与给我属性错误的代码相同。
  • 我应该在该线程上添加回复或评论说它不起作用吗?
  • 这样的评论(绝对不是答案!)将详细说明您尝试过的内容以及您的环境(例如,通过指向此 Q 的指针)可能会帮助其他人,所以这绝不是一个坏主意.
  • 这能回答你的问题吗? How to read a single character from the user?

标签: python curses msvcrt getch


【解决方案1】:

您可以使用termiossystty 包定义自己的getch 版本:

def getch():
    import termios
    import sys, tty
    def _getch():
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch
    return _getch()

【讨论】:

  • termios.error: (25, 'Inappropriate ioctl for device')
  • 最后需要返回_getch()(你忘了括号)
  • 显然 termios 在 Windows 系统上不存在。有什么方法可以从 perl 中调整 Term::ReadKey 并在 Windows 上运行?
【解决方案2】:

这是一个测试(在 RPi,Py 3 上)代码,无需按 Enter 按钮即可读取指定长度的字符

但是考虑一件事:

这必须在终端上运行,否则会引发错误

import termios, sys , tty
def _getch():
   fd = sys.stdin.fileno()
   old_settings = termios.tcgetattr(fd)
   try:
      tty.setraw(fd)
      ch = sys.stdin.read(1)     #This number represents the length
   finally:
      termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
   return ch
getch = _getch()
print(getch)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    • 2017-02-19
    • 2016-06-20
    • 1970-01-01
    相关资源
    最近更新 更多