def win_getpass(prompt='Password: ', stream=None):
"""Prompt for password with echo off, using Windows getch()."""
if sys.stdin is not sys.__stdin__:
return fallback_getpass(prompt, stream)
import msvcrt
for c in prompt:
msvcrt.putch(c)
pw = ""
while 1:
c = msvcrt.getch()
if c == '\r' or c == '\n':
break
if c == '\003':
raise KeyboardInterrupt
if c == '\b':
pw = pw[:-1]
else:
pw = pw + c
msvcrt.putch('\r')
msvcrt.putch('\n')
return pw
python类getch()的实例源码
def pwd_input():
print 'password:',
chars=[]
while True:
try:
newChar=msvcrt.getch().decode('utf-8')
except:
print u'??????cmd????????????.'
return raw_input('password:')
if newChar in '\r\n':
break
elif newChar=='\b':
if chars:
del chars[-1]
msvcrt.putch('\b'.encode('utf-8')) # ??????
msvcrt.putch(' '.encode('utf-8')) # ??????
msvcrt.putch('\b'.encode('utf-8')) # ????
else:
chars.append(newChar)
msvcrt.putch('*'.encode('utf-8')) # ????
return ''.join(chars)
def review_thumbnail(self):
""" Display image and give user prompt to keep or discard """
fname = self.download('thumb')['thumb']
imgcat = os.getenv('IMGCAT', None)
if imgcat is None:
raise Exception("Set $IMGCAT to a terminal display program")
cmd = '%s %s' % (imgcat, fname)
print(cmd)
os.system(cmd)
print("Press Y to keep, N to delete, or any key to quit")
while True:
char = getch()
if char.lower() == 'y':
return True
elif char.lower() == 'n':
return False
raise Exception('Cancel')
def win_getpass(prompt='Password: ', stream=None):
"""Prompt for password with echo off, using Windows getch()."""
if sys.stdin is not sys.__stdin__:
return fallback_getpass(prompt, stream)
import msvcrt
for c in prompt:
msvcrt.putch(c)
pw = ""
while 1:
c = msvcrt.getch()
if c == '\r' or c == '\n':
break
if c == '\003':
raise KeyboardInterrupt
if c == '\b':
pw = pw[:-1]
else:
pw = pw + c
msvcrt.putch('\r')
msvcrt.putch('\n')
return pw
def read_character():
"""Read one character from stdin. Returns -1 when no input is available."""
if sys.stdin.isatty():
# we're in console, read a character from the user
char = getch()
# check for ctrl-c (break)
if ord(char) == 3:
sys.stdout.write("^C")
sys.stdout.flush()
raise KeyboardInterrupt
else: return char
else:
# input is redirected using pipes
char = sys.stdin.read(1)
# return -1 if there is no more input available
return char if char != "" else -1
def getpass_getpass(prompt='Password:', stream=None):
try:
import msvcrt
except ImportError:
return _realgetpass(prompt, stream)
password = ''
sys.stdout.write(prompt)
while True:
ch = msvcrt.getch()
if ch == '\b':
if password:
password = password[:-1]
sys.stdout.write('\b \b')
else:
continue
elif ch == '\r':
sys.stdout.write(os.linesep)
return password
else:
password += ch
sys.stdout.write('*')
def getpass_getpass(prompt='Password:', stream=None):
try:
import msvcrt
except ImportError:
return _realgetpass(prompt, stream)
password = ''
sys.stdout.write(prompt)
while True:
ch = msvcrt.getch()
if ch == '\b':
if password:
password = password[:-1]
sys.stdout.write('\b \b')
else:
continue
elif ch == '\r':
sys.stdout.write(os.linesep)
return password
else:
password += ch
sys.stdout.write('*')
def get_pager_start(pager, start):
"""Return the string for paging files with an offset.
This is the '+N' argument which less and more (under Unix) accept.
"""
if pager in ['less','more']:
if start:
start_string = '+' + str(start)
else:
start_string = ''
else:
start_string = ''
return start_string
# (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
def adinput(prompt, default=None):
putstr(prompt)
if default is None:
data = []
else:
data = list(default)
putstr(data)
while True:
c = getch()
if c in '\r\n':
break
elif c == '\003': # Ctrl-C
putstr('\r\n')
raise KeyboardInterrupt
elif c == '\b': # Backspace
if data:
putstr('\b \b') # Backspace and wipe the character cell
data.pop()
elif c in '\0\xe0': # Special keys
getch()
else:
putch(c)
data.append(c)
putstr('\r\n')
return ''.join(data)
def win_getpass(prompt='Password: ', stream=None):
"""Prompt for password with echo off, using Windows getch()."""
if sys.stdin is not sys.__stdin__:
return fallback_getpass(prompt, stream)
import msvcrt
for c in prompt:
msvcrt.putch(c)
pw = ""
while 1:
c = msvcrt.getch()
if c == '\r' or c == '\n':
break
if c == '\003':
raise KeyboardInterrupt
if c == '\b':
pw = pw[:-1]
else:
pw = pw + c
msvcrt.putch('\r')
msvcrt.putch('\n')
return pw
def __call__(self):
import msvcrt
return msvcrt.getch()
def sanity_checks(self):
# if run on platform that isn't windows
if os.name != 'nt':
print 'This program is currently only windows compatible. Sorry!'
exit()
# if drive not attached
if not os.path.exists(self.ghost_drive):
print self.ghost_drive + ' not attached'
exit()
# disallow c:\ drive
if self.args['source'] == 'c':
print "You probably don't want to be ghosting c:/ drive..."
exit()
# prevent recursive copying
if self.normalise_backslash(self.args['source']) in self.normalise_backslash(self.args['dest']):
print 'destination is part of the ghost - please see recursion in a dictionary'
exit()
# prompt if dest is root
#if save_dir:
if len(self.args['dest']) == 3:
print "Are you sure that you want to copy to the root of the drive? y/n"
answer = msvcrt.getch()
if answer.lower() == 'y':
pass
else:
exit()
############################### General Purpose #############################################
def get_char():
while msvcrt.kbhit():
msvcrt.getch()
func = False
char = msvcrt.getch()
if char in ('\x00', '\xE0'):
func = True
while func:
msvcrt.getch()
func = False
char = msvcrt.getch()
if char in ('\x00', '\xE0'):
func = True
return char.replace('\r', '\n')
def alarm(seconds):
time.sleep(seconds)
while msvcrt.kbhit():
msvcrt.getch()
while not msvcrt.kbhit():
winsound.Beep(440, 250)
time.sleep(0.25)
def get_char():
while msvcrt.kbhit():
msvcrt.getch()
func = False
char = msvcrt.getch()
if char in ('\x00', '\xE0'):
func = True
while func:
msvcrt.getch()
func = False
char = msvcrt.getch()
if char in ('\x00', '\xE0'):
func = True
return char.replace('\r', '\n')
def get_int():
while msvcrt.kbhit():
msvcrt.getch()
buff = ''
char = msvcrt.getch()
while char != '\r' or not buff:
if '0' <= char <= '9':
sys.stdout.write(char)
buff += char
char = msvcrt.getch()
sys.stdout.write('\n')
return int(buff)
################################################################################
def __call__(self):
import msvcrt
return msvcrt.getch()
def _GetchWindows():
# This reads only one character.
from msvcrt import getch
return getch()
def getchar(echo):
rv = msvcrt.getch()
if echo:
msvcrt.putchar(rv)
_translate_ch_to_exc(rv)
if PY2:
enc = getattr(sys.stdin, 'encoding', None)
if enc is not None:
rv = rv.decode(enc, 'replace')
else:
rv = rv.decode('cp1252', 'replace')
return rv
def getch(): # getchar(), getc(stdin) #PYCHOK flake
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
return ch