如何在Python的父进程和派生子进程之间共享数据? [英] How do you share data between a parent and forked child process in Python?
问题描述
我很确定有人会使用os.plock(op)函数来做到这一点,但是我不知道如何做到这一点.另外,如果有更好的方法,我将不胜感激.代码段非常受欢迎.
I'm pretty sure one would do this using the os.plock(op) function, but I have no idea how. Also, if there's a better way, I'd be grateful to find out. Code snippets are very welcome.
推荐答案
Subprocess 替换了os. popen,os.system,os.spawn,popen2和命令. 用于管道的简单示例为:
Subprocess replaces os.popen, os.system, os.spawn, popen2 and commands. A simple example for piping would be:
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
您还可以使用带有标志= MAP_SHARED的内存映射文件进程之间.
You could also use a memory mapped file with the flag=MAP_SHARED for shared memory between processes.
多重处理都将共享内存,并提供了更高级别的接口.取自处理文档:
multiprocessing abstracts both pipes and shared memory and provides a higher level interface. Taken from the Processing documentation:
from multiprocessing import Process, Pipe
def f(conn):
conn.send([42, None, 'hello'])
conn.close()
if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p = Process(target=f, args=(child_conn,))
p.start()
print parent_conn.recv() # prints "[42, None, 'hello']"
p.join()
这篇关于如何在Python的父进程和派生子进程之间共享数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!