I am trying to give input to a process when it is required but I am not able to. To make it easier and generate the input request I am using the windows "date" command, which gives as output the current date and then asks as input a new date.
Using this code, the execution is blocked as there is no EOF on the line read where it asks the input, so this is not a good solution (unless I am doing something wrong). With this one I dont even get the line where input is required, probably because there is no EOF:
import  subprocess 
with subprocess.Popen(['date'], stdin=subprocess.PIPE, text=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT, shell=True,close_fds=True) as process:
    
    for line in iter(process.stdout.readline,""):
        print(line)
        if "Enter the new date:" in line:
            process.stdin.write("20/04/2022\n")
                        continue
if process.returncode != 0:
    raise subprocess.CalledProcessError(process.returncode, process.args)
After reading tons and trying many options I reach the next code. With communicate I am able to read even the line where input is required so I can take action at that point (writing input). the problem is that when I try to write the input I get errors.
import  subprocess 
cmd=(['date'])
with Popen(cmd, stdin=PIPE,stdout=PIPE, shell=True, stderr=STDOUT, universal_newlines=True) as p:
    for line in p.communicate():
        print(line)
        if "Enter the new" in line:
            p.stdin.write("20/04/2022\n")                         #this should write the input....
            # data_write=p.communicate(input="20/04/2022\n")[0]   #another option I have tried
            # p.communicate(input="20/04/2022\n".encode())        #another option I have tried
            
if p.returncode != 0:
    raise CalledProcessError(p.returncode, p.args)`
With the first option I get the following error
I/O operation on closed file.
With the second option I get the following error:
Cannot send input after starting communication
And with the third one I get:
Cannot send input after starting communication
Anyone knows where I am messing up? This looks so simple but so frustrating ........
SOLUTION:
Following Aran's answer I changed the code to make it work, at least for this specific case. Code below:
import  subprocess 
cmd=(['date'])
p=Popen(cmd, stdin=PIPE,stdout=PIPE, shell=True, stderr=STDOUT, universal_newlines=True) 
    
while p.poll() is None:  #while the process is running.....
    p.stdin.write("20/04/2022\n")
    p.stdin.close()
    for line in p.communicate():
        print(line)
        if line!=None:
            # print(line) # process line here
            if "Escriba la nueva fecha:" in line:
                print("respuesta")
                # p.stdin.write("20/04/2022\n")
                # data_write=p.communicate(input="20/04/2022\n")[0]
                # p.communicate(input="20/04/2022\n".encode())
if p.returncode != 0:
    raise CalledProcessError(p.returncode, p.args)