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() 子进程


- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01