读取/写入 Popen() 子进程

Reading/writing to a Popen() subprocess(读取/写入 Popen() 子进程)
本文介绍了读取/写入 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() 子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)