Home  >  Article  >  Backend Development  >  python中管道用法入门实例

python中管道用法入门实例

WBOY
WBOYOriginal
2016-06-06 11:18:031359browse

本文实例讲述了python中管道用法。分享给大家供大家参考。具体如下:

#!coding=utf-8
import multiprocessing
def consumer(pipe):
  output_p , input_p = pipe
  input_p.close() #关闭管道的输入端
  while True:
    try:
      item = output_p.recv()
    except EOFError:
      break
    print item
  print ("consumer done")
#生产项目并将其放到队列上
def producer(sequence, input_p):
  for item in sequence:
    input_p.send(item)
if __name__ == "__main__":
  #创建管道
  (output_p , input_p ) = multiprocessing.Pipe()
  #启动使用者进程
  cons_p = multiprocessing.Process(target=consumer, args=((output_p , input_p ),))
  cons_p.start()
  #关闭生产者中的输出管道
  output_p.close()
  #生产项目
  sequence = [1,2,3,4]
  producer(sequence, input_p)
  #关闭输入管道,表示完成
  input_p.close()
  #等待使用者进行关闭
  cons_p.join()

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn