ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: how to implement kbhit() on Linux
Submitter: Nelson Rush (other recipes)
Last Updated: 2008/05/03
Version no: 1.1
Category:

 

5 stars 1 vote(s)


Description:

kbhit on linux, the sample just prints dots until you press any key. I updated the sample to show how to implement unbuffered getch and getche safely.

Source: Text Source

import sys, termios, atexit
from select import select

# save the terminal settings
fd = sys.stdin.fileno()
new_term = termios.tcgetattr(fd)
old_term = termios.tcgetattr(fd)

# new terminal setting unbuffered
new_term[3] = (new_term[3] & ~termios.ICANON & ~termios.ECHO)

# switch to normal terminal
def set_normal_term():
    termios.tcsetattr(fd, termios.TCSAFLUSH, old_term)

# switch to unbuffered terminal
def set_curses_term():
    termios.tcsetattr(fd, termios.TCSAFLUSH, new_term)

def putch(ch):
    sys.stdout.write(ch)

def getch():
    return sys.stdin.read(1)

def getche():
    ch = getch()
    putch(ch)
    return ch

def kbhit():
    dr,dw,de = select([sys.stdin], [], [], 0)
    return dr <> []

if __name__ == '__main__':
    atexit.register(set_normal_term)
    set_curses_term()

    while 1:
        if kbhit():
            ch = getch()
            break
        sys.stdout.write('.')

    print 'done'

Discussion:

Why? Maybe you want to know if the user is typing before you bother to perform a getch().

Context? The sort of situation you would use this in is where you need non-blocking keyboard input. This example essentially peeks at the keyboard buffer to see if there is any text available without blocking.

The example with the dots is lousy, but it suffices. I'm absolutely certain you'll put it to better use. I hope this helps someone.

Note: In my example I force the terminal back to its original buffered state. However, if you ever accidently forget to do this yourself, keep in mind you can still type 'reset' at the Linux prompt to get things back to normal. As you are typing it you will not see the text, but it is being typed so do not worry.



Add comment

No comments.



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. Wrapping template engine ...

4. Assignment in expression

5. SOLVING THE METACLASS ...

6. Povray for python

7. Calling Windows API ...

8. Generic filter logic ...

9. Function Decorators by ...

10. MS SQL Server log monitor




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.