[PATCH 1 of 3] getch() -- to read one keystroke from console

Kirill Smelkov kirr at mns.spb.ru
Wed Dec 26 03:15:16 CST 2007


В сообщении от 26 декабря 2007 08:05 Bryan O'Sullivan написал(a):
> > +# getch, taken from
> > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 +class
> > _Getch:
>
> This code is horribly overcomplicated.  Please follow the coding style
> in the util and util_win32 modules, add the code there, use the normal
> demandimport machinery, and keep it simple instead of introducing those
> classes.

I agree, here is reworked patch:


# HG changeset patch
# User Kirill Smelkov <kirr at mns.spb.ru>
# Date 1198660364 -10800
# Node ID c97ad3bf11f90bf72227d8726589f0d6587db56d
# Parent  7182bb4c0dc5133373c0540570f56e71e39a2b50
getch() -- to read one keystroke from console

Idea taken from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892

diff --git a/mercurial/util.py b/mercurial/util.py
--- a/mercurial/util.py
+++ b/mercurial/util.py
@@ -1078,6 +1078,11 @@ if os.name == 'nt':
         except NameError:
             pass
 
+    def getch():
+        '''Gets a single character from standard input.  Does not echo to the
+        screen.'''
+        return msvcrt.getch()
+
     try:
         # override functions with win32 versions if possible
         from util_win32 import *
@@ -1087,6 +1092,7 @@ if os.name == 'nt':
         pass
 
 else:
+    import tty, termios
     nulldev = '/dev/null'
 
     def rcfiles(path):
@@ -1262,6 +1268,18 @@ else:
 
     def set_signal_handler():
         pass
+
+    def getch():
+        '''Gets a single character from standard input.  Does not echo to the
+        screen.'''
+        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
 
 def find_exe(name, default=None):
     '''find path of an executable.





More information about the Mercurial-devel mailing list