2

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?

Mircea Ispas
  • 20,260
  • 32
  • 123
  • 211
  • Seems to be the same issue as this: https://stackoverflow.com/questions/24544353/python-getpass-getpass-function-call-hangs – JimmyJames Jan 04 '19 at 21:28
  • @Felics edited my answer which didn't work for a completely different solution which seems to work on MSYS at least. – Jean-François Fabre Jan 04 '19 at 21:33
  • @Jean-FrançoisFabre The issue is the same: "it can't receive the input from standard input" – JimmyJames Jan 04 '19 at 21:35
  • yes, but the solution isn't: "As a workaround I can use the script from PowerShell". OP knows it is a terminal issue but OP would like to avoid switching terminals – Jean-François Fabre Jan 04 '19 at 21:36
  • Found a solution here: https://stackoverflow.com/questions/32597209/python-not-working-in-the-command-line-of-git-bash: `alias python='winpty python.exe'` – JimmyJames Jan 04 '19 at 21:37
  • @Jean-FrançoisFabre Right, I didn't say it was the solution. I said it was the same issue. – JimmyJames Jan 04 '19 at 21:38

2 Answers2

3

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

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
3

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

JimmyJames
  • 1,356
  • 1
  • 12
  • 24