Running an interactive command from within Python

Viewed 43402

I have a script that I want to run from within Python (2.6.5) that follows the logic below:

  • Prompts the user for a password. It looks like ("Enter password: ") (*Note: Input does not echo to screen)
  • Output irrelevant information
  • Prompt the user for a response ("Blah Blah filename.txt blah blah (Y/N)?: ")

The last prompt line contains text which I need to parse (filename.txt). The response provided doesn't matter (the program could actually exit here without providing one, as long as I can parse the line).

My requirements are somewhat similar to Wrapping an interactive command line application in a Python script, but the responses there seem a bit confusing, and mine still hangs even when the OP mentions that it doesn't for him.

Through looking around, I've come to the conclusion that subprocess is the best way of doing this, but I'm having a few issues. Here is my Popen line:

p = subprocess.Popen("cmd", shell=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
  • When I call a read() or readline() on stdout, the prompt is printer to the screen and it hangs.

  • If I call a write("password\n") for stdin, the prompt is written to the screen and it hangs. The text in write() is not written (I don't the cursor move the a new line).

  • If I call p.communicate("password\n"), same behavior as write()

I was looking for a few ideas here on the best way to input to stdin and possibly how to parse the last line in the output if your feeling generous, though I could probably figure that out eventually.

3 Answers

If you just want a user to enter a password without it being echoed to the screen just use the standard library's getpass module:

import getpass
print("You entered:", getpass.getpass())

NOTE:The prompt for this function defaults to "Password: " also this will only work on command lines where echoing can be controlled. So if it doesn't work try running it from terminal.

Related