Where should the " if __name__ = '__main__' " idiom be placed when using the Python multiprocessing module?

StackOverflow https://stackoverflow.com/questions/23642166

  •  22-07-2023
  •  | 
  •  

Question

I am running Windows 7.

In my main module, I call a function, A, which is in module a.

import a

a.A(listOfInputTuplesForB)

A calls multiple instances of the function B:

import multiprocessing as mp

def A(listOfInputTuplesForB):
    if __name__ == '__main__':
        pool = mp.Pool(processes = mp.cpu_count())
        pool.map(poolWrapperForB, listOfInputTuplesForB)
        pool.close()
        pool.join()

def poolWrapperForB(inputTuple):
    return B(*inputTuple)

def B(arg1, arg2, arg3):
    print "I did nothing with my arguments!"

Now, obviously, when I run my main module, nothing happens, as the conditional if __name__ == '__main__' fails, since __name__ == 'a'.

Where should if __name__ == '__main__' go in this program?

Was it helpful?

Solution

Remove main from def A(listOfInputTuplesForB): and put it in the other file.

import a

if __name__ == "__main__":
  a.A(listOfInputTuplesForB)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top