我有这个简单的python代码来获取密码而不回应它。
import getpass
password = getpass.getpass("Password: ")
print(password)
这段代码在Linux上运行正常,但在Windows Git Bash上,它让我无限期地输入。作为一种解决方法,我可以使用PowerShell中的脚本,但是为了运行脚本而更改shell非常烦人。
您是否知道Python中的任何其他非回显库或此问题的任何解决方法?
答案 0 :(得分:2)
适用于我的MSYS / Git bash终端,getpass
或使用mscvrt
的解决方案不能打印字符(并且不捕获它们)
import subprocess,sys
sys.stdout.write("Password: ")
sys.stdout.flush()
subprocess.check_call(["stty","-echo"])
password = input()
subprocess.check_call(["stty","echo"])
print("\npassword: {}".format(password))
诀窍是致电stty
取消输出,使用标准input()
来电获取密码,然后再次使用stty
打开输出
答案 1 :(得分:1)
一般问题似乎与此类似:Python getpass.getpass() function call hangs,即python无法从stdio读取。这里的答案是:Python not working in the command line of git bash有一个对我有用的解决方案:
alias python='winpty python.exe'
这通常可以解决从stdio读取的问题,从而使getpass能够按预期工作。
这种方法在尝试重定向到文件时会导致另一个错误:stdout is not a tty
将别名更改为此已解决的问题:
alias python='winpty -Xallow-non-tty python.exe'
如对此答案的解释:https://superuser.com/questions/1011597/what-does-an-output-is-not-a-tty-error-mean