与另一个进程的标准输入/输出交互 [英] Interact with standard input/output of another process

查看:34
本文介绍了与另一个进程的标准输入/输出交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可执行文件 example.exe.此可执行文件的行为如下:

I have an executable example.exe. This executable's behaviour is as follows:

1.Waits for input from user
2.Performs some operations, based on input
3.goto 1

如何使用 subprocess 或类似模块与可执行文件交互?

How can I use subprocess or a similar module to interact with executable?

我希望运行该流程,插入输入,接收输出,然后根据接收到的输出插入其他输入.

I wish to run the process, insert input, receive output, then insert additional inputs based on the output received.

推荐答案

from subprocess import Popen, PIPE

process = Popen([r'path/to/process', 'arg1', 'arg2', 'arg3'], stdin=PIPE, stdout=PIPE)

to_program = "something to send to the program's stdin"
while process.poll() == None:  # While not terminated
    process.stdin.write(to_program)

    from_program = process.stdout.readline()  # Modify as needed to read custom amount of output
    if from_program == "something":  # send something new based on stdout
       to_program = "new thing to send to program"
    else:
       to_program = "other new thing to send to program"

print("Process exited with code {}".format(process.poll()))

这篇关于与另一个进程的标准输入/输出交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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