Python prompt for user with echo and password without echo

Why not just use raw_input for the username:

import getpass

user = raw_input("Username:")
passwd = getpass.getpass("Password for " + user + ":")

print("Got", user, passwd)

Demo:

Username:iCodez
Password for iCodez:
('Got', 'iCodez', 'secret')

There is another alternative, which I found documented here. Detect whether the input stream is a TTY, and change your input method based on that information.

I used something like this:

#!/usr/bin/python

import sys
import getpass

if sys.stdin.isatty():
   print "Enter credentials"
   username = raw_input("Username: ")
   password = getpass.getpass("Password: ")
else:
   username = sys.stdin.readline().rstrip()
   password = sys.stdin.readline().rstrip()

print "Username: [%s], password [%s]" % (username, password)

This works fine from a terminal:

bash> ./mytest.py
Enter credentials
Username: one
Password:
Username: [one], password [two]

for piped input:

bash> echo "one
> two" | ./mytest.py
Username: [one], password [two]

for input from a file:

bash> echo "one" > input
bash> echo "two" >> input
bash> ./mytest.py < input
Username: [one], password [two]

and also for a heredoc:

bash> ./mytest.py << EOF
> one
> two
> EOF
Username: [one], password [two]

Personally, that covers all of my needs.