When using multiprocessing with Windows, we must have if __name__ == '__main__':. For example:
# Script1.py
import multiprocessing
class Test(object):
def __init__(self, x):
self.x = x
def square(self, i, return_jobs, x):
i = x**2
return_jobs[i] = i
def run(self):
if __name__ == "__main__":
manager = multiprocessing.Manager()
return_jobs = manager.dict()
jobs = []
for i in range(len(self.x)):
p = multiprocessing.Process(target = self.square, args=(i, return_jobs , self.x[i]) )
jobs.append(p)
p.start()
for proc in jobs:
print(proc)
proc.join()
print('result',return_jobs.values())
Test([2, 3]) .run()
This simple example script ran fine and return something like: result [4, 9]. However, if I have have a different script and import Script1 and use Test then it won't work. That is,
# Script2.py
from Script1.py import Test
class Test2(object):
def __init__(self, y):
self.y = y
def run(self):
z = Test(self.y).run()
will not invoke the function Test(self.y).run() at all. However, if I place the class Test2 in the same script as Test (# Script1.py ) then all is fine.
What is the best way to fix this? The Script1.py is a subprocess of the overall code. I don't want to have to combine these scripts together...
I should also note that I am using Spyder as well. This could be a problem.