在Unix中无法读取Python中的单个字符(提取样式) [英] Reading a single character (getch style) in Python is not working in Unix

查看:95
本文介绍了在Unix中无法读取Python中的单个字符(提取样式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我在 http://code.activestate.com/recipes/134892使用食谱时,/我似乎无法正常工作.它总是会引发以下错误:

Any time I use the recipe at http://code.activestate.com/recipes/134892/ I can't seem to get it working. It always throws the following error:

Traceback (most recent call last):
    ...
    old_settings = termios.tcgetattr(fd)
termios.error: (22, 'Invalid argument)

我最好的想法是,因为我在Eclipse中运行它,所以termios使文件描述符变得合适.

My best thought is that it is because I'm running it in Eclipse so termios is throwing a fit about the file descriptor.

推荐答案

这适用于Ubuntu 8.04.1,Python 2.5.2,但我没有得到这样的错误.可能是您应该从命令行尝试它,eclipse可能正在使用它自己的stdin,如果从Wing IDE运行它,我会得到完全相同的错误,但是从命令行来看,它的效果很好. 原因是IDE(例如Wing)正在使用自己的类netserver.CDbgInputStream作为sys.stdin 所以sys.stdin.fileno为零,这就是为什么会出错. 基本上,IDE stdin不是tty(print sys.stdin.isatty()为False)

This is working on Ubuntu 8.04.1 , Python 2.5.2, i get no such error. May be you should try it from command line, eclipse may be using its own stdin, i get exact same error if I run it from Wing IDE, but from command line it works great. Reason is that IDE e.g Wing is using there own class netserver.CDbgInputStream as sys.stdin so sys.stdin.fileno is zero, thats why the error. Basically IDE stdin is not a tty (print sys.stdin.isatty() is False)

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 = _GetchUnix()

print getch()

这篇关于在Unix中无法读取Python中的单个字符(提取样式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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