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

2
  • Can you share what is the value of cmd that you are executing? Commented Sep 7, 2021 at 2:43
  • its a custom written exe with some command line arguments, which after few minutes asks for confirmation, and then proceeds execution further Commented Sep 7, 2021 at 9:09

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
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.
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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.