20:30追記せっかちな人は続 PYTHON 2.7 の GETPASS.PYをお読み下さい。そうでないなら、順にどーぞ。
Python 2.7 のgetpass — 可搬性のあるパスワード入力機構は下らないところでマズくて。プロンプトに Unicode 使えない。特に Windows でマズくて、プロンプトのみならず Unicode 使えない。
Python3.xでは FIX されているので、そのまま持って来れないかなぁ、と思った。
Mercurial > cpython view Lib/getpass.py @ 87173:c3896275c0f6(3.3.3のもの)より持ってくる(「raw」からダウンロードすればいい)。名前は好きにすれば良いと思うが、Python 2.7 のために必要な改造は2行追加のみ:
1 from __future__ import unicode_literals
2 from __future__ import print_function
一応「3.3.3」に対しての、全部載っけとく:
1 """Utilities to get a password and/or the current user name.
2
3 getpass(prompt[, stream]) - Prompt for a password, with echo turned off.
4 getuser() - Get the user name from the environment or password database.
5
6 GetPassWarning - This UserWarning is issued when getpass() cannot prevent
7 echoing of the password contents while reading.
8
9 On Windows, the msvcrt module will be used.
10 On the Mac EasyDialogs.AskPassword is used, if available.
11
12 """
13 from __future__ import unicode_literals
14 from __future__ import print_function
15
16 # Authors: Piers Lauder (original)
17 # Guido van Rossum (Windows support and cleanup)
18 # Gregory P. Smith (tty support & GetPassWarning)
19
20 import os, sys, warnings
21
22 __all__ = ["getpass","getuser","GetPassWarning"]
23
24
25 class GetPassWarning(UserWarning): pass
26
27
28 def unix_getpass(prompt='Password: ', stream=None):
29 """Prompt for a password, with echo turned off.
30
31 Args:
32 prompt: Written on stream to ask for the input. Default: 'Password: '
33 stream: A writable file object to display the prompt. Defaults to
34 the tty. If no tty is available defaults to sys.stderr.
35 Returns:
36 The seKr3t input.
37 Raises:
38 EOFError: If our input tty or stdin was closed.
39 GetPassWarning: When we were unable to turn echo off on the input.
40
41 Always restores terminal settings before returning.
42 """
43 fd = None
44 tty = None
45 try:
46 # Always try reading and writing directly on the tty first.
47 fd = os.open('/dev/tty', os.O_RDWR|os.O_NOCTTY)
48 tty = os.fdopen(fd, 'w+', 1)
49 input = tty
50 if not stream:
51 stream = tty
52 except EnvironmentError as e:
53 # If that fails, see if stdin can be controlled.
54 try:
55 fd = sys.stdin.fileno()
56 except (AttributeError, ValueError):
57 passwd = fallback_getpass(prompt, stream)
58 input = sys.stdin
59 if not stream:
60 stream = sys.stderr
61
62 if fd is not None:
63 passwd = None
64 try:
65 old = termios.tcgetattr(fd) # a copy to save
66 new = old[:]
67 new[3] &= ~termios.ECHO # 3 == 'lflags'
68 tcsetattr_flags = termios.TCSAFLUSH
69 if hasattr(termios, 'TCSASOFT'):
70 tcsetattr_flags |= termios.TCSASOFT
71 try:
72 termios.tcsetattr(fd, tcsetattr_flags, new)
73 passwd = _raw_input(prompt, stream, input=input)
74 finally:
75 termios.tcsetattr(fd, tcsetattr_flags, old)
76 stream.flush() # issue7208
77 except termios.error:
78 if passwd is not None:
79 # _raw_input succeeded. The final tcsetattr failed. Reraise
80 # instead of leaving the terminal in an unknown state.
81 raise
82 # We can't control the tty or stdin. Give up and use normal IO.
83 # fallback_getpass() raises an appropriate warning.
84 del input, tty # clean up unused file objects before blocking
85 passwd = fallback_getpass(prompt, stream)
86
87 stream.write('\n')
88 return passwd
89
90
91 def win_getpass(prompt='Password: ', stream=None):
92 """Prompt for password with echo off, using Windows getch()."""
93 if sys.stdin is not sys.__stdin__:
94 return fallback_getpass(prompt, stream)
95 import msvcrt
96 for c in prompt:
97 msvcrt.putwch(c)
98 pw = ""
99 while 1:
100 c = msvcrt.getwch()
101 if c == '\r' or c == '\n':
102 break
103 if c == '\003':
104 raise KeyboardInterrupt
105 if c == '\b':
106 pw = pw[:-1]
107 else:
108 pw = pw + c
109 msvcrt.putwch('\r')
110 msvcrt.putwch('\n')
111 return pw
112
113
114 def fallback_getpass(prompt='Password: ', stream=None):
115 warnings.warn("Can not control echo on the terminal.", GetPassWarning,
116 stacklevel=2)
117 if not stream:
118 stream = sys.stderr
119 print("Warning: Password input may be echoed.", file=stream)
120 return _raw_input(prompt, stream)
121
122
123 def _raw_input(prompt="", stream=None, input=None):
124 # This doesn't save the string in the GNU readline history.
125 if not stream:
126 stream = sys.stderr
127 if not input:
128 input = sys.stdin
129 prompt = str(prompt)
130 if prompt:
131 stream.write(prompt)
132 stream.flush()
133 # NOTE: The Python C API calls flockfile() (and unlock) during readline.
134 line = input.readline()
135 if not line:
136 raise EOFError
137 if line[-1] == '\n':
138 line = line[:-1]
139 return line
140
141
142 def getuser():
143 """Get the username from the environment or password database.
144
145 First try various environment variables, then the password
146 database. This works on Windows as long as USERNAME is set.
147
148 """
149
150 for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
151 user = os.environ.get(name)
152 if user:
153 return user
154
155 # If this fails, the exception will "explain" why
156 import pwd
157 return pwd.getpwuid(os.getuid())[0]
158
159 # Bind the name getpass to the appropriate function
160 try:
161 import termios
162 # it's possible there is an incompatible termios from the
163 # McMillan Installer, make sure we have a UNIX-compatible termios
164 termios.tcgetattr, termios.tcsetattr
165 except (ImportError, AttributeError):
166 try:
167 import msvcrt
168 except ImportError:
169 getpass = fallback_getpass
170 else:
171 getpass = win_getpass
172 else:
173 getpass = unix_getpass
unix_getpass は 3.3.4 以降のものが、contextlib のインターフェイスの違いで、動かない。なお、3.3.3 のものは、Mac での「from EasyDialogs import AskPassword」をかわりにつかうのをやめているみたい。ワタシ、生涯とおして一度として Mac ユーザであったことはないので良くわからないけど。
msvcrt.getch()、msvcrt.putch() ではなく msvcrt.getwch()、msvcrt.putwch() に変更されたのは 2007 年なのだが、Python 2.7 では取り込まれてない。msvcrt 関数は C 拡張なので 2.7 時点で既にバイトなのか unicode なのかは区別していて、msvcrt.getwch()、msvcrt.putwch() に置換するだけでは 2.7 ではエラーになる。これはこういうこと:
1 Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win32
2 Type "help", "copyright", "credits" or "license" for more information.
3 >>> type("aaa")
4 <type 'str'>
5 >>> type(u"aaa")
6 <type 'unicode'>
7 >>>
ので getwchar()、putwchar() は「str」(Python 3.x での bytes そのもの)を拒絶する。
1 from __future__ import unicode_literals
はこのためのもの。
なお、
1 from __future__ import print_function
は、「Python 2.x から Python 3.x で大き過ぎる破壊された互換性」のいくつかのうち、一番有名で一番しょーもなくて、一番対処しやすいやつ。あたしゃ print に括弧つける癖がついちまったよ。