前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 使用管道在进程间通信 脚本

python 使用管道在进程间通信 脚本

作者头像
用户5760343
发布2022-05-13 17:21:43
6690
发布2022-05-13 17:21:43
举报
文章被收录于专栏:sktj

multiprocessing

"""

Use multiprocess anonymous pipes to communicate. Returns 2 connection

object representing ends of the pipe: objects are sent on one end and

received on the other, though pipes are bidirectional by default

"""

import os

from multiprocessing import Process, Pipe

def sender(pipe):

"""

send object to parent on anonymous pipe

"""

pipe.send(['spam'] + [42, 'eggs'])

pipe.close()

def talker(pipe):

"""

send and receive objects on a pipe

"""

pipe.send(dict(name='Bob', spam=42))

reply = pipe.recv()

print('talker got:', reply)

if name == 'main':

(parentEnd, childEnd) = Pipe()

Process(target=sender, args=(childEnd,)).start() # spawn child with pipe

print('parent got:', parentEnd.recv()) # receive from child

parentEnd.close() # or auto-closed on gc

代码语言:javascript
复制
(parentEnd, childEnd) = Pipe()
child = Process(target=talker, args=(childEnd,))
child.start()
print('parent got:', parentEnd.recv())                  # receieve from child
parentEnd.send({x * 2 for x in 'spam'})                 # send to child
child.join()                                            # wait for child exit
print('parent exit')
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • multiprocessing
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档