[英]Can't get multiprocessing to work with my class instances in Python
[英]I can't seem to get multiprocessing to work on my laptop
这是我第一次在 stackoverflow 上发帖,所以我希望我不要搞砸了。
我是 Python 的初学者,我想尝试多处理。 但是我花了两天时间学习了有关它的基本教程,但似乎没有一个按照我想要的方式工作。 我正在尝试的一个例子:
import os
from multiprocessing import Process, current_process
def square(number):
result = number * number
proc_id = os.getpid()
print(f"Process ID: {proc_id}")
process_name = current_process().name
print(f"Process Name: {process_name}")
print(f"The number {number} squares to {result}.")
if __name__ == "__main__":
processes = []
numbers = [1, 2, 3, 4, 5]
for i, number in enumerate(numbers):
process = Process(target=square, args=(number,))
processes.append(process)
process.start()
for process in processes:
process.join()
一个简单的代码,但编译器上的所有内容都是空白的。
但是,如果我在这里更改这一行:
process = Process(target=square, args=(number,))
到:
process = Process(target=square(number))
它现在有效! 但是输出将是错误的。
我的理想输出
Process ID: 10000
Process Name: Process - 1
The number 1 squares to 1.
Process ID: 10001
Process Name: Process - 2
The number 2 squares to 4.
Process ID: 10002
Process Name: Process - 3
The number 3 squares to 9.
Process ID: 10003
Process Name: Process - 4
The number 4 squares to 16.
实际产量
Process ID: 10000
Process Name: MainProcess
The number 1 squares to 1.
Process ID: 10000
Process Name: MainProcess
The number 2 squares to 4.
Process ID: 10000
Process Name: MainProcess
The number 3 squares to 9.
Process ID: 10000
Process Name: MainProcess
The number 4 squares to 16.
我使用的是 Windows 10、Visual Studio 2019、Python 3.7。
我不确定解决方案是否简单,但我的大脑是方形的,我需要帮助。
创建multiprocessing.Process
,子进程继承父stdout
的stdout
并可以写入。 问题是,标准输出可能不会去任何你可以阅读的地方。 当您从 IDE 之类的 GUI 运行时,标准输出通常会重定向到遗忘。 IDE 检测正在运行的进程以获取其对sys.stdout
写入并重定向到命令输出窗口,但这不会流向子进程。
不幸的是,没有一种简单的方法可以在multiprocessin.Process
获取标准输出流。 它很容易,当你只是通过像执行不同的程序subprocess
。
好消息是,子进程一开始就想写入标准输出的情况很少见。 multiprocessing
有几个选项,例如Queue
和Pipe
来将事情返回给父进程。
这不是你问的问题,但我强烈建议你尽可能使用multiprocessing.Pool
。 它为您节省了很多麻烦和簿记。 你的整个__main__
将是
from multiprocessing import Pool
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5]
with Pool() as pool:
pool.map(square, numbers)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.