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: '):
19 """Prompt for a password, with echo turned off.
21 Restore terminal settings at end.
25 fd
= sys
.stdin
.fileno()
27 return default_getpass(prompt
)
29 getpass
= default_getpass
30 old
= termios
.tcgetattr(fd
) # a copy to save
33 new
[3] = new
[3] & ~termios
.ECHO
# 3 == 'lflags'
35 termios
.tcsetattr(fd
, termios
.TCSADRAIN
, new
)
36 passwd
= _raw_input(prompt
)
38 termios
.tcsetattr(fd
, termios
.TCSADRAIN
, old
)
40 sys
.stdout
.write('\n')
44 def win_getpass(prompt
='Password: '):
45 """Prompt for password with echo off, using Windows getch()."""
52 if c
== '\r' or c
== '\n':
55 raise KeyboardInterrupt
65 def default_getpass(prompt
='Password: '):
66 print "Warning: Problem with getpass. Passwords may be echoed."
67 return _raw_input(prompt
)
70 def _raw_input(prompt
=""):
71 # A raw_input() replacement that doesn't save the string in the
72 # GNU readline history.
76 sys
.stdout
.write(prompt
)
77 line
= sys
.stdin
.readline()
86 """Get the username from the environment or password database.
88 First try various environment variables, then the password
89 database. This works on Windows as long as USERNAME is set.
95 for name
in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
96 user
= os
.environ
.get(name
)
100 # If this fails, the exception will "explain" why
102 return pwd
.getpwuid(os
.getuid())[0]
104 # Bind the name getpass to the appropriate function
112 from EasyDialogs
import AskPassword
114 getpass
= default_getpass
116 getpass
= AskPassword
118 getpass
= win_getpass
120 getpass
= unix_getpass