2

If I run a terminal command from Python using subprocess, how do I print the password prompt?

I have a Python script that asks users to authenticate via Kerberos. My program is basically this:

import subprocess

def kinit():
  kinit = "kinit -f"
  prompt = subprocess.check_output(kinit, shell=True)
  print prompt   ## echoes "Password for username@domain.com" AFTER pw input

if __name__=="__main__":
  kinit()
  doOtherStuff()

When this script is launched from the Terminal, the program waits for password input (which can be input via the command line), but it only displays the "Password for username@domain.com" prompt AFTER the user inputs their password.

Do you know how I can display the "Password for username@domain.com" before the Python script waits for them to input their password?

Alvaro Silvino
  • 9,441
  • 12
  • 52
  • 80
touch my body
  • 1,634
  • 22
  • 36

2 Answers2

3

It's an interactive thing, so you shouldn't be calling check_output. That is usually used for subprocesses which will do some stuff and then terminate (without keyboard input required).

You can do what you want by making a Popen instance instead, and then interacting with it using Popen.communicate. But it can be tricky to send input to the process stdin, and read lines from it's stdout correctly without deadlocking or buffering complications.

And there is a better way: pexpect is great for this. I recommend to ditch subprocess in favour of pexpect here.

wim
  • 338,267
  • 99
  • 616
  • 750
  • This is the right answer. Trying to make it work with subprocess is just going to lead to a great deal of frustration – Logan Jan 06 '16 at 19:17
  • Thanks for explaining (1) why `check_output` is less than ideal, and (2) that `Popen` and `pexpect` are more optimal solutions. I will try these and see how they work. – touch my body Jan 06 '16 at 20:04
  • @Logan: `pexpect` is preferrable due to [these reasons](http://pexpect.readthedocs.org/en/stable/FAQ.html#whynotpipe) but [it doesn't mean that `subprocess` can't be used in interactive case](http://stackoverflow.com/a/23795689/4279) – jfs Jan 07 '16 at 08:18
  • You're absolutely right, it is entirely possible, but just more difficult – Logan Jan 07 '16 at 12:43
-1

Turns out you can't. subprocess will not return output in the middle of a process, and the process will not complete until you input user input.

touch my body
  • 1,634
  • 22
  • 36