1

With Python 3.11.4, when I use subprocess.run or subprocess.Popen to accept "silent" input or "secure input" and then hit ctrl+c, using regular input afterwards doesn't display text being typed. Here's a reproducible example:

import subprocess

try:
    print("hit ctrl+c")
    result = subprocess.run("echo $(read -s)", shell=True)
except KeyboardInterrupt:
    pass

text = input("Text typed here is not visible: ")
print(text)

Here's my attempt, using Popen, to kill the process (but to no avail):

import subprocess

result = subprocess.Popen("echo $(read -s)", shell=True)
try:
    print("hit ctrl+c")
    result.wait()
except KeyboardInterrupt:
    result.kill()
    pass

text = input("Text typed here is not visible: ")
print(text)

How do I go about properly ending the process waiting for silent input so that regular input afterwards is displayed as it's typed?

Edit: I should clarify that I'm building an interface which uses subprocess to interact with a specific command line tool. That tool prompts the user for input in a "silent" fashion, but I was able to reproduce the problem using echo $(read -s) in its place.

heygarrett
  • 11
  • 4
  • Is there a reason you're using a subprocess for this instead of the built-in `getpass` module? – Barmar Jun 21 '23 at 16:39
  • @Barmar Apologies, I should have clarified that I'm using subprocess to query a command line tool that prompts the user for "silent" input. I've updated my initial post. – heygarrett Jun 21 '23 at 17:44
  • This is technically a bug in your command-line tool; it disables terminal echoing but doesn't re-enable it before exiting. – chepner Jun 21 '23 at 17:47
  • @chepner That very well could be the case. Using my contrived example, how would I go about re-enabling terminal echoing? If I can better understand that I'll have an easier time investigating a potential bug in the command-line tool I'm using. – heygarrett Jun 21 '23 at 17:55
  • The simplest solution would probably be to execute `reset`, but will also do things like change the current foreground and background colors back to the terminal default, if they've been changed. A more targeted solution would be to execute (I think) `stty echo`. – chepner Jun 21 '23 at 18:32
  • @chepner `os.sytem("stty echo")` works! Thanks! – heygarrett Jun 26 '23 at 00:04

1 Answers1

1

It sounds like you might be looking for getpass?

from getpass import getpass

getpass("Text typed here is not visible: ")
webelo
  • 1,646
  • 1
  • 14
  • 32
  • Apologies, as I mentioned in another comment I should have clarified that I'm using subprocess to query a command line tool that prompts the user for "silent" input. I've updated my initial post. – heygarrett Jun 21 '23 at 17:45