Improved some error messages for command line processing.
[python/dscho.git] / Lib / getpass.py
blobbe7a2f9049b769aa51148088b0410f505ed8b228
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 Authors: Piers Lauder (original)
7 Guido van Rossum (Windows support and cleanup)
8 """
11 def getpass(prompt='Password: '):
12 """Prompt for a password, with echo turned off.
14 Restore terminal settings at end.
16 On Windows, this calls win_getpass(prompt) which uses the
17 msvcrt module to get the same effect.
19 """
21 import sys
22 try:
23 import termios, TERMIOS
24 except ImportError:
25 try:
26 import msvcrt
27 except ImportError:
28 return default_getpass(prompt)
29 else:
30 return win_getpass(prompt)
32 fd = sys.stdin.fileno()
33 old = termios.tcgetattr(fd) # a copy to save
34 new = old[:]
36 new[3] = new[3] & ~TERMIOS.ECHO # 3 == 'lflags'
37 try:
38 termios.tcsetattr(fd, TERMIOS.TCSADRAIN, new)
39 passwd = _raw_input(prompt)
40 finally:
41 termios.tcsetattr(fd, TERMIOS.TCSADRAIN, old)
43 sys.stdout.write('\n')
44 return passwd
47 def win_getpass(prompt='Password: '):
48 """Prompt for password with echo off, using Windows getch()."""
49 import msvcrt
50 for c in prompt:
51 msvcrt.putch(c)
52 pw = ""
53 while 1:
54 c = msvcrt.getch()
55 if c == '\r' or c == '\n':
56 break
57 if c == '\003':
58 raise KeyboardInterrupt
59 if c == '\b':
60 pw = pw[:-1]
61 else:
62 pw = pw + c
63 msvcrt.putch('\r')
64 msvcrt.putch('\n')
65 return pw
68 def default_getpass(prompt='Password: '):
69 return _raw_input(prompt)
72 def _raw_input(prompt=""):
73 # A raw_input() replacement that doesn't save the string in the
74 # GNU readline history.
75 import sys
76 prompt = str(prompt)
77 if prompt:
78 sys.stdout.write(prompt)
79 line = sys.stdin.readline()
80 if not line:
81 raise EOFError
82 if line[-1] == '\n':
83 line = line[:-1]
84 return line
87 def getuser():
88 """Get the username from the environment or password database.
90 First try various environment variables, then the password
91 database. This works on Windows as long as USERNAME is set.
93 """
95 import os
97 for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
98 user = os.environ.get(name)
99 if user:
100 return user
102 # If this fails, the exception will "explain" why
103 import pwd
104 return pwd.getpwuid(os.getuid())[0]