天天看点

python 进程间通信【转】

附:能够成功实现进程间通信的sample例程:

#程序A

#产生子进程B(receiver.py),并向其发送字符串

 import subprocess, time

 subproc = subprocess.Popen(['python', 'receiver.py'], stdin=subprocess.PIPE, shell=True)   #运行子进程B

   time.sleep(0.5)

   print ‘start’

   #下面两种方法都可以了

   subproc.stdin.write(‘data\n’)

   subproc.communicate(‘data\n’)

   print ‘end’

#程序B receiver.py

#从stdin读字符串并打印之。

   import sys

   print ‘receive…’

   s = sys.stdin.readline()

   print ‘get:’, len(s), s

执行A得到返回结果:

start

receive…

get: data

end