还有另一种选择,我发现有文档记录的here。检测输入流是否为TTY,并根据该信息更改输入方法。
我用了这样的东西:#!/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)
这在终端上运行良好:bash> ./mytest.py
Enter credentials
Username: one
Password:
Username: [one], password [two]
对于管道输入:bash> echo "one
> two" | ./mytest.py
Username: [one], password [two]
对于文件输入:bash> echo "one" > input
bash> echo "two" >> input
bash> ./mytest.py < input
Username: [one], password [two]
对于遗传性卵巢癌:bash> ./mytest.py << EOF
> one
> two
> EOF
Username: [one], password [two]
就我个人而言,这涵盖了我所有的需要。