How to give input multiple times to another program on python

前端 未结 2 651
死守一世寂寞
死守一世寂寞 2021-01-26 04:55

I want to make python file which opens two programs. This two programs have to get input from each other multiple times. I opened two programs and know how to give input to one

2条回答
  •  暖寄归人
    2021-01-26 05:18

    Try using write and communicate to send data to cmd_1 and cmd_2 and get the response, see https://docs.python.org/3/library/subprocess.html#popen-constructor.

    for i in range(n):
        cmd_1 = subprocess.Popen("./p1",shell = True,stdin = subprocess.PIPE,stdout = subprocess.PIPE,stderr = subprocess.PIPE)
        cmd_2 = subprocess.Popen("./p2",shell = True,stdin = subprocess.PIPE,stdout = subprocess.PIPE,stderr = subprocess.PIPE)
        cmd_1.stdin.write(cmd_input[n])
        cmd_2.stdin.write(cmd_input[n])
        cmd1_stdout, cmd1_stderr = cmd_1.communicate()
        cmd2_stdout, cmd2_stderr = cmd_2.communicate()
        for line in cmd1_stdout:
            print(line.decode('ascii'))
        for line in cmd2_stdout:
            print(line.decode('ascii'))
    

提交回复
热议问题