Python 语言对管道的支持
我想在 python 中实现这样的东西:
def producer():
while True:
sys.stdout.write("this is my data\n")
def consumer():
while True:
data = sys.stdin.read()
print data
producer | consumer
管道实际上需要创建两个进程,连接 stdout 和 stdin,并运行它们直到两者终止。
python 中是否有像 shell 那样的语法支持,或者我是否需要递归到 Popen 对象?
Popen
最简单的实现是什么?
有人可以提供一个可用于实现此管道模式的通用类吗?该类将具有与此类似的签名:
Class Pipe:
def __init__(self, process1, process2, ...):
因此,就我而言,可以按如下方式使用:
mypipe = Pipe(producer, consumer)
I would like to implement in python something like this:
def producer():
while True:
sys.stdout.write("this is my data\n")
def consumer():
while True:
data = sys.stdin.read()
print data
producer | consumer
The pipe actually needs to create two processes, connect stdout and stdin, and run them until both terminate.
Is there syntactical support for that in python, as the shell has, or do I need to recurse to the Popen
object?
What is the simplest implementation in terms of Popen
?
Could somebody offer a generic class which can be used to implement this piping pattern? The class would have a signature similar to this:
Class Pipe:
def __init__(self, process1, process2, ...):
So that, in my case, could be used as follows:
mypipe = Pipe(producer, consumer)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 pipes 模块:
当然,语法与 shell 管道不同,但为什么要重新发明轮子呢?
You can use the pipes module:
Sure, the syntax won't be the same as a shell pipe, but why reinvent the wheel?
您可能会想到协程。看看 David Beazley 的非常有趣的演示。
You may be thinking of coroutines. Check out this very interesting presentation by David Beazley.