[PATCH 2 of 4] getch() -- to read one keystroke from console

Kirill Smelkov kirr at mns.spb.ru
Thu Dec 27 07:48:37 CST 2007


# HG changeset patch
# User Kirill Smelkov <kirr at mns.spb.ru>
# Date 1198762400 -10800
# Node ID 17f113422432bda71e9fbf7c743736ee7c7ed8c2
# Parent  a1395546023ce2c1f4efa28e19c6348ee0b8efc8
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