Reading/writing to a Popen() subprocess(读取/写入 Popen() 子进程)
问题描述
我正在尝试使用 python subprocess.Popen() 调用与子进程交谈.在我的真实代码中,我正在实现一种 IPC,所以我想写入一些数据、读取响应、写入更多数据、读取响应等等.因此,我不能使用 Popen.communicate(),否则它适用于简单的情况.
I'm trying to talk to a child process using the python subprocess.Popen() call. In my real code, I'm implementing a type of IPC, so I want to write some data, read the response, write some more data, read the response, and so on. Because of this, I cannot use Popen.communicate(), which otherwise works well for the simple case.
这段代码显示了我的问题.它甚至从来没有得到第一个响应,挂在第一个阅读结果"上.为什么?我怎样才能使这项工作如我所愿?
This code shows my problem. It never even gets the first response, hangs at the first "Reading result". Why? How can I make this work as I expect?
import subprocess
p = subprocess.Popen(["sed", 's/a/x/g'],
stdout = subprocess.PIPE,
stdin = subprocess.PIPE)
p.stdin.write("abc
")
print "Reading result:"
print p.stdout.readline()
p.stdin.write("cat
")
print "Reading result:"
print p.stdout.readline()
推荐答案
如果可以的话,我会尝试使用 Popen().communicate(),因为它为你做了很多好事,但是如果您需要完全按照您的描述使用 Popen(),则需要使用 -l 选项将 sed 设置为在换行符之后刷新其缓冲区:
I would try to use Popen().communicate() if you can as it does a lot of nice things for you, but if you need to use Popen() exactly as you described, you'll need to set sed to flush its buffer after newlines with the -l option:
p = subprocess.Popen(['sed', '-l', 's/a/x/g'],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE)
你的代码应该可以正常工作
and your code should work fine
这篇关于读取/写入 Popen() 子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:读取/写入 Popen() 子进程
基础教程推荐
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 包装空间模型 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
