[英]Python Multiprocessing Start Process in Module Other Than Main
I have three modules, worker
, master
, and MainTests
. 我有三个模块,
worker
, master
和MainTests
。 I'm running the MainTests
module as the main script. 我正在运行
MainTests
模块作为主要脚本。 In MainTests
, I call master.run()
, inside of which I need to spawn multiple worker
processes. 在
MainTests
,我调用master.run()
,在其中需要生成多个worker
进程。 Is this possible? 这可能吗? In all the python
multiprocessing
tutorials I have come across, processes are started in the main module. 在我遇到的所有python
multiprocessing
教程中,过程都是在主模块中启动的。 If this is possible, could someone provide an example as to what this might look like? 如果可能的话,有人可以提供一个例子说明一下吗?
This is what I have attempted so far: 到目前为止,这是我尝试过的:
Worker.py 工人
import time
class Worker(object):
def __init__(self):
super(Worker, self).__init__()
def run(self):
time.sleep(5)
print("worker done with run")
return
Master.py: Master.py:
import multiprocessing
class Master(object):
def __init__(self, workers_array):
super(Master, self).__init__()
self.workers_array = workers_array
def run(self):
process_arr = [multiprocessing.Process(worker.run()) for worker in self.workers_array]
[worker_process.start() for worker_process in process_arr]
MainTests.py MainTests.py
from Worker import *
from Master import *
workers_array = [Worker() for i in range(5)]
master = Master(workers_array)
master.run()
Two issues arise: 出现两个问题:
Thanks in advance for any help. 在此先感谢您的帮助。
I'm not sure if you're still locking for an answer but you just have to put the "entry point" of your main program in this if statement: 我不确定您是否仍在锁定答案,但是您只需要在以下if语句中输入主程序的“入口点”即可:
if __name__ == "__main__":
main()
This way you can start a process in an imported module. 这样,您可以在导入的模块中启动流程。 For further information check out this bit of the docs and obviously everything else in there :)
有关更多信息,请查看文档的这一部分以及其中的所有其他内容:)
In your example it would be: 在您的示例中,它将是:
from Worker import *
from Master import *
if __name__ == __main__:
workers_array = [Worker() for i in range(5)]
master = Master(workers_array)
master.run()
This has worked for me. 这对我有用。 Hope I could help.
希望我能帮上忙。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.