gpt4 book ai didi

具有多个标准输入写入的 python popen.communicate()

转载 作者:行者123 更新时间:2023-11-28 19:26:56 34 4
gpt4 key购买 nike

我有一个外部进程,我试图从 python 触发,然后通过 Popen.stdin.communicate() 发送信息。我正在与之交谈的进程向 stdout 写入几行,然后提示用户通过 stdin(一个数字)输入,然后它写入几行 ore 并提示通过 stdin 进行第二次输入。我想用一个 python 脚本替换手动输入,该脚本将为我自动执行此操作。到目前为止,我有以下代码可以很好地提交第一轮用户输入:

working_file = subprocess.Popen(["/pyRoot/iAmACrashyProgram"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
working_file.communicate(input=b'3')[0]

子进程按预期运行,然后提示输入第二个输入,不幸的是,communicate() 似乎不允许您向标准输入写入多次。接下来我尝试用这个替换上一行:

working_file = subprocess.Popen(["/pyRoot/iAmACrashyProgram"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
working_file.stdin.write(b'3')
working_file.stdin.write(b'7')

我没有得到任何错误,所以大概数据正在某处,但子进程没有获取数据(我知道这一点,因为当它接收到该数据时,它会写入日志文件)。显然我不理解某些东西,我想更好地理解 communicate() 在幕后做了什么,这样我就可以找到另一种写入标准输入的方法,但我发现这个对象的文档有点难以理解。我也不是缓冲区和流方面的专家,所以这让我很困惑。

任何人都可以阐明通信对象的工作原理以及我如何能够做一些类似但具有多次写入的事情。还有人知道哪里是阅读流和缓冲区的好地方吗?

非常感谢

最佳答案

根据 python 的 documentation :

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

关于具有多个标准输入写入的 python popen.communicate(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8493102/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com