need definitive answer: capture a keypress
Andrei Kulakov
sill at optonline.net
Wed Aug 15 13:46:32 EDT 2001
On Wed, 15 Aug 2001 08:16:11 -0400, robin at brainexeculink.com <robin at brainexeculink.com> wrote:
> This question comes up so often, it's ridiculous. I've read all the
> Deja threads to no avail.
>
> How can one capture a keypress at the console, in a cross-platform
> manner?
>
> In Win32, I simply use getch() and kbhit() from msvcrt. Works great.
>
> On Linux, I can use curses and getch(). But there appears to be no way
> of checking for a hit, equivalent to kbhit().
>
> What is worse, curses appears to interact badly with the standard
> print statement, and for the life of me I can't figure out how to get
> sequential text formatted in a nice simple "print" way, using curses.
>
> There's more: curses leaves my terminal in an unusable state, even
> after Python exits. I find this module unusable.
Did you use curses.wrapper() ? It should set your term to normal state.
>
> Surely there is an extension that provides can capture a keypress,
> without getting into the wild world of curses?
Yes, this is in the FAQ on python.org. It's a bit messy, it uses termios
and it's different from 2.0 and 2.1:
self.fd = sys.stdin.fileno()
self.new_term = termios.tcgetattr(self.fd)
self.old_term = termios.tcgetattr(self.fd)
# set up curses-like terminal state (no echo, read one char at a time)
if sys.version_info[0] == 2 and sys.version_info[1] == 0:
self.new_term[3] = (self.new_term[3] & ~TERMIOS.ICANON &
~TERMIOS.ECHO)
else:
self.new_term[3] = (self.new_term[3] & ~termios.ICANON &
~termios.ECHO)
def set_normal_term(self):
"""Set 'normal' terminal settings"""
if sys.version_info[0] == 2 and sys.version_info[1] == 0:
termios.tcsetattr(self.fd, TERMIOS.TCSAFLUSH, self.old_term)
else:
termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_term)
def set_curses_term(self):
"""Set 'normal' terminal settings"""
if sys.version_info[0] == 2 and sys.version_info[1] == 0:
termios.tcsetattr(self.fd, TERMIOS.TCSAFLUSH, self.new_term)
else:
termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.new_term)
- Andrei
>
> -----
> robin
> robin at brainexeculink.com
> (remove "brain" to reply)
--
Cymbaline: intelligent learning mp3 player - python, linux, console.
it at: cy.silmarill.org
More information about the Python-list
mailing list