如何在python多处理中覆盖打印



我有一个类AlternativePrinter,它覆盖了python的打印函数(在这个例子中,它附加了"[write to terminal]"但是由于某种原因,从多处理进程中打印的任何东西都不会经过这个打印函数。我怎样才能使所有的打印,包括从过程,通过我的新打印机?

import multiprocessing as mp
import sys
import time
class AlternativePrinter:
def __init__(self):
self.old_stdout = sys.stdout
sys.stdout = self
# executed when the user does a `print`
def write(self, text):
self.old_stdout.write("n[write to terminal]"+text)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
sys.stdout = self.old_stdout
def flush(self):
self.old_stdout.flush()
def wait_and_print(seconds):
time.sleep(seconds)
print("I waited for", seconds, "seconds")
return seconds
if __name__ == "__main__":
with AlternativePrinter():
print('Initiating simultaneous processes:')
pool = mp.Pool(4)
input = [(4,),(2,)]
results = pool.starmap(wait_and_print, input)
pool.close()
pool.join()
for result in results:
print(result)

输出:

[write to terminal]Initiating simultaneous processes:
[write to terminal]
I waited for 2 seconds
I waited for 4 seconds
[write to terminal]4
[write to terminal]
[write to terminal]2
[write to terminal]

结束

wait_and_print中添加with AlternativePrinter():if __name__ == "__main__":下面的行不会在子进程中执行,因此永远不会使用AlternativePrinter()。

相关内容

  • 没有找到相关文章

最新更新