如何多次向python上的另一个程序提供输入 [英] How to give input multiple times to another program on python

查看:31
本文介绍了如何多次向python上的另一个程序提供输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作打开两个程序的python文件.这两个程序必须多次相互获取输入.我打开了两个程序并知道如何为一个程序提供输入,但我不知道如何在一个程序上多次输入并多次获得输出.我的代码是这样的.

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 program, but i don't know how to give input multiple time on one program and get output multiple time. My code is like this.

subprocess.call("/usr/bin/gcc -o p1 "+path1,shell=True)
subprocess.call("/usr/bin/gcc -o p2 "+path2,shell=True)
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)
std_out_1 = cmd_1.stdout
std_out_2 = cmd_2.stdout
for line in std_out_1.readlines():
    print(line.decode('ascii'))
for line in std_out_2.readlines():
    print(line.decode('ascii'))

现在这个程序只是获取程序输出.我想为每个程序提供 N 次输入并获得 N 次输出.所以我希望我的代码是这样的.

Now this program just get program output. I want to give input N times for each program and get output N times. So I expect my code to be like this.

give_input(n)
for i in range(n):
    t_1 = get_output(t_2) //give input t_2, and get output t_1
    t_2 = get_output(t_1) //give input t_1, and get output t_2

推荐答案

尝试使用 writecommunicate 将数据发送到 cmd_1cmd_2 并得到响应,见 https://docs.python.org/3/library/subprocess.html#popen-constructor.

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'))

这篇关于如何多次向python上的另一个程序提供输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆