Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python getpass doesn't work on Windows Git Bash (MINGW64)

Tags:

python

windows

I have this simple python code to get a password without echoing it.

import getpass

password = getpass.getpass("Password: ")
print(password)

This code works as expected on Linux, but on Windows Git Bash it let's me type indefinitely. As a workaround I can use the script from PowerShell, but it's annoying to change shells just to run a script.

Do you know any other non-echoing libraries in Python or any workaround for this issue?

like image 283
Mircea Ispas Avatar asked May 04 '26 18:05

Mircea Ispas


2 Answers

The general issue seems to be similar to this: Python getpass.getpass() function call hangs i.e. python isn't able to read from stdio. An answer here: Python not working in the command line of git bash has a solution that worked for me:

alias python='winpty python.exe'

This fixes issues with reading from stdio in general allowing getpass to work as expected.

This approach leads to another error when attempting to redirect to file: stdout is not a tty Changing the alias to this resolved that issue:

alias python='winpty -Xallow-non-tty python.exe'

As explained in an answer to this: https://superuser.com/questions/1011597/what-does-an-output-is-not-a-tty-error-mean

like image 66
JimmyJames Avatar answered May 06 '26 08:05

JimmyJames


That works with my MSYS/Git bash terminal, where getpass or solutions using mscvrt don't and print characters (and don't capture them)

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))

the trick is to call stty to suppress output, get the password using a standard input() call, then turn on output with stty again

like image 44
Jean-François Fabre Avatar answered May 06 '26 07:05

Jean-François Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!