I had to quickly learn Python. I can’t solve a simple (I think) task: on a Linux system, start a child process of another program and redirect it to stdin, stdout to its own, respectively, stdout and stdin. It is fundamentally important that the program live and not die after a single write-read transaction. In short, you need to set up a long-term command-response interaction. You cannot also use a shell (that is, setting up channels through the shell), only programmatically.
I write something like this:
import subprocess proc = subprocess.Popen(['myprog', '-l'], shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE) #допустим, я сохранил proc и через какое-то время пытаюсь с ним взаимодействовать: if proc.returncode == None: proc.stdin.write(b'command') response = process.communicate()[0] If you run this code once, it will return an empty string. If looped, raises BrokenPipeError. This behavior is incomprehensible to me.
Why such code does not work? communicate () waiting for the process to complete? But if this is so, then why is the verification if proc.returncode == None valid? The process is alive. What can I do to make this work (tell me at least what to use)?
shell=Trueif you send the command as a list (this is an error in most cases). You probably want to send the line containing the command to either removeshell=True2 - why you expect thatprocess.returncode is not NoneBEFORE you calledprocess.communicate()(AFTER theprocessreturns this function is dead) 3-process.communicate(input=b'command')passes the command, closes the stdin stream, reads the output and waits until the child process terminates, returning its output. - jfs