From 9a9703242e7c547b48db93f1bf0ff892be1bba4e Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Fri, 4 Aug 2017 13:26:03 +0530 Subject: [PATCH] Refactor the fixed getpass into its own module --- src/calibre/srv/manage_users_cli.py | 28 ++-------------------- src/calibre/utils/getpass.py | 36 +++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 26 deletions(-) create mode 100644 src/calibre/utils/getpass.py diff --git a/src/calibre/srv/manage_users_cli.py b/src/calibre/srv/manage_users_cli.py index 719dbe2a1e..4162688d63 100644 --- a/src/calibre/srv/manage_users_cli.py +++ b/src/calibre/srv/manage_users_cli.py @@ -8,7 +8,7 @@ import sys from functools import partial from calibre import prints -from calibre.constants import preferred_encoding, iswindows +from calibre.constants import preferred_encoding # Manage users CLI {{{ @@ -70,31 +70,7 @@ def manage_users_cli(path=None): return get_valid(_('Enter the username'), validate) def get_pass(username): - - def getpass(prompt): - if iswindows: - # getpass is broken on windows with python 2.x and unicode, the - # below implementation is from the python 3 source code - import msvcrt - for c in prompt: - msvcrt.putwch(c) - pw = "" - while 1: - c = msvcrt.getwch() - if c == '\r' or c == '\n': - break - if c == '\003': - raise KeyboardInterrupt - if c == '\b': - pw = pw[:-1] - else: - pw = pw + c - msvcrt.putwch('\r') - msvcrt.putwch('\n') - return pw - else: - from getpass import getpass - return getpass(prompt).decode(enc) + from calibre.utils.getpass import getpass while True: one = getpass( diff --git a/src/calibre/utils/getpass.py b/src/calibre/utils/getpass.py new file mode 100644 index 0000000000..887938ad6e --- /dev/null +++ b/src/calibre/utils/getpass.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python2 +# vim:fileencoding=utf-8 +# License: GPLv3 Copyright: 2017, Kovid Goyal + +from __future__ import absolute_import, division, print_function, unicode_literals + +import sys + +from calibre.constants import iswindows, preferred_encoding + + +def getpass(prompt): + if iswindows: + # getpass is broken on windows with python 2.x and unicode, the + # below implementation is from the python 3 source code + import msvcrt + for c in prompt: + msvcrt.putwch(c) + pw = "" + while 1: + c = msvcrt.getwch() + if c == '\r' or c == '\n': + break + if c == '\003': + raise KeyboardInterrupt + if c == '\b': + pw = pw[:-1] + else: + pw = pw + c + msvcrt.putwch('\r') + msvcrt.putwch('\n') + return pw + else: + enc = getattr(sys.stdin, 'encoding', preferred_encoding) or preferred_encoding + from getpass import getpass + return getpass(prompt).decode(enc)