1

I am trying to run following code

process = subprocess.Popen(args=cmd, shell=True, stdout=subprocess.PIPE)
while process.poll() is None:
   stdoutput = process.stdout.readline()
   print(stdoutput.decode())
   if '(Y/N)' in stdoutput.decode():
       process.communicate(input=b'Y\n')

this cmd argument runs for a few minutes after which it prompts for a confirmation, but the process.communicate is not working, neither is process.stdin.write()

How do I send input string 'Y' to this running process when it prompts for confirmation

phileinSophos
  • 362
  • 4
  • 22

2 Answers2

1

Per the doc on Popen.communicate(input=None, timeout=None):

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE.

Please try that, and if it's not sufficient, do indicate what the symptom is.

Jerry101
  • 12,157
  • 5
  • 44
  • 63
  • i updated the program, but still this doesnt work, the script/process ends the moment it encounters `popen.communicate()`, there's no error, but the prompt fails the process terminates – phileinSophos Sep 07 '21 at 09:15
  • I'd think up many hypotheses about what could be going wrong and a way to test each. Maybe this code is not properly detecting the "Y/N" prompt, so print something before it calls `process.communicate()`. Maybe the subprocess is not receiving the input text or didn't get the newline or something, so make it print the input text or set a breakpoint in it, or substitute a small test command. Maybe the subprocess is failing for another reason like OutOfMemory -- so print the `process.poll()` return code and the `process.communicate()` return tuple. Also see @NielGodfreyPonciano's answer. – Jerry101 Sep 07 '21 at 19:25
1

On top of the answer from @Jerry101, if the subprocess that you are calling is a python script that uses the input(), be aware that as documented:

If the prompt argument is present, it is written to standard output without a trailing newline.

Thus if you perform readline() as in process.stdout.readline(), it would hang there waiting for the new line \n character as documented:

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string

A quick fix is append the newline \n when requesting the input() e.g. input("(Y/N)\n") instead of just input("(Y/N)").

Related question: