1 """Utilities to get a password and/or the current user name.
3 getpass(prompt) - prompt for a password, with echo turned off
4 getuser() - get the user name from the environment or password database
6 On Windows, the msvcrt module will be used.
7 On the Mac EasyDialogs.AskPassword is used, if available.
11 # Authors: Piers Lauder (original)
12 # Guido van Rossum (Windows support and cleanup)
16 __all__
= ["getpass","getuser"]
18 def unix_getpass(prompt
='Password: ', stream
=None):
19 """Prompt for a password, with echo turned off.
20 The prompt is written on stream, by default stdout.
22 Restore terminal settings at end.
28 fd
= sys
.stdin
.fileno()
30 return default_getpass(prompt
)
32 old
= termios
.tcgetattr(fd
) # a copy to save
35 new
[3] = new
[3] & ~termios
.ECHO
# 3 == 'lflags'
37 termios
.tcsetattr(fd
, termios
.TCSADRAIN
, new
)
38 passwd
= _raw_input(prompt
, stream
)
40 termios
.tcsetattr(fd
, termios
.TCSADRAIN
, old
)
46 def win_getpass(prompt
='Password: ', stream
=None):
47 """Prompt for password with echo off, using Windows getch()."""
48 if sys
.stdin
is not sys
.__stdin
__:
49 return default_getpass(prompt
, stream
)
56 if c
== '\r' or c
== '\n':
59 raise KeyboardInterrupt
69 def default_getpass(prompt
='Password: ', stream
=None):
70 print >>sys
.stderr
, "Warning: Problem with getpass. Passwords may be echoed."
71 return _raw_input(prompt
, stream
)
74 def _raw_input(prompt
="", stream
=None):
75 # A raw_input() replacement that doesn't save the string in the
76 # GNU readline history.
82 line
= sys
.stdin
.readline()
91 """Get the username from the environment or password database.
93 First try various environment variables, then the password
94 database. This works on Windows as long as USERNAME is set.
100 for name
in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
101 user
= os
.environ
.get(name
)
105 # If this fails, the exception will "explain" why
107 return pwd
.getpwuid(os
.getuid())[0]
109 # Bind the name getpass to the appropriate function
112 # it's possible there is an incompatible termios from the
113 # McMillan Installer, make sure we have a UNIX-compatible termios
114 termios
.tcgetattr
, termios
.tcsetattr
115 except (ImportError, AttributeError):
120 from EasyDialogs
import AskPassword
122 getpass
= default_getpass
124 getpass
= AskPassword
126 getpass
= win_getpass
128 getpass
= unix_getpass