import sys
from cStringIO import StringIO
from multiprocessing import Process, Queue
def mp():
queue = Queue()
p = Process(target=loop,args=('lo','op'))
q = Process(target=doop,args=('do','op'))
p.start()
q.start()
p.join()
q.join()
def loop(p,x):
old_stdout = sys.stdout # Redirection of the printing output to a StringIO
sys.stdout = mystdout = StringIO()
for i in xrange(100):
print p + x
### Write the code\functions necessary in here. ###
sys.stdout = old_stdout
dataStats_1 = mystdout.getvalue() # Put all the redirected output into a string.
def doop(q,y):
old_stdout = sys.stdout # Redirection of the printing output to a StringIO()
sys.stdout = mystdout = StringIO()
for i in xrange(100):
print q+y
### Write the code\functions necessary in here. ###
sys.stdout = old_stdout
dataStats_2 = mystdout.getvalue()
if __name__ == "__main__":
mp()
したがって、各 dataStats_1 および dataStats_2 変数には、関数「doop」および「loop」からの出力が含まれます。
この上記の方法がどれほど本物かはわかりません。しかし、これは実際に私にとってはうまくいきます。
また、プロセスの代わりにスレッドを使用しようとすると、印刷出力を StringIO にリダイレクトするこの方法は機能しません。スレッドは親の I/O ソースを継承し、特定のスレッドでそれを変更すると変更されるためです。親スレッドにも。ただし、子プロセスの場合、親の I/O ソースに干渉しません。だから、これはうまくいきます。