passing user input from main to python in a pool

making this work portably (i.e. under Windows) is somewhat fiddly, but this should do the right thing:

from multiprocessing import Pool

def init(*args):
   global var1
   [var1] = args

def process(path):
    print(repr(var1), 'processing', path)

def MCprocess():
    var1 = input("enter input: ")
    with Pool(initializer=init, initargs=[var1]) as pool:
        pool.map(process, ['first', 'second'])

if __name__ == '__main__':
    MCprocess()

note that if you just care about Linux or OSX (i.e. where it forks processes) you could get away with:

from multiprocessing import Pool

def process(path):
    print(repr(var1), 'processing', path)

var1 = input("enter input: ")
with Pool() as pool:
    pool.map(process, ['first', 'second'])

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top