python multiprocessing not working at all

10,398

Your code should actually result in an error. The args argument to multiprocessing.Process() does not open a process for each argument, it just supplies the arguments in the list to a single function and then calls that function in a child process. To run 5 separate instances like that, you would have to do something like this:

import multiprocessing

def worker(number):
    print number
    return

if __name__ == '__main__':
    procs = []

    for i in range(5):
        procs.append(multiprocessing.Process(target=worker, args=[i]))

    [proc.start() for proc in procs]
Share:
10,398

Related videos on Youtube

CatfishKrenz
Author by

CatfishKrenz

Updated on June 04, 2022

Comments

  • CatfishKrenz
    CatfishKrenz almost 2 years

    So I took the following code, ran it, and literally nothing happened. Python acted like it had finished everything (maybe it did) but nothing printed. Any help getting this to work would be greatly appreciated!

    import multiprocessing
    
    def worker(number):
        print number
        return
    
    if __name__ == '__main__':
        test = multiprocessing.Process(target=worker, args=[0,1,2,3,4])
        test.start()
    
  • CatfishKrenz
    CatfishKrenz about 11 years
    Okay, I just tried that code and it also just returned, didn't print anything. Not sure as to why.
  • Alex V
    Alex V about 11 years
    What OS are you using? How are you running the program (IDLE, the python command followed by the name of the file containing the source code, etc)? I ran that code on Ubuntu 12.04 with Python 2.7.3 and it printed the numbers as expected.
  • Alex V
    Alex V about 11 years
    The problem is with IDLE. As the last comment to the answer at stackoverflow.com/a/2774623/407861 says, "Well, IDLE is a strange thing. In order to 'capture' everything what you write using print statements or sys.stdout.write, IDLE "overrides" sys.stdout and replaces it with an object that passes everything back to IDLE so it can print it. I guess when you are starting a new process from multiprocessing, this hackery is not inherited by the child process, therefore you don't see anything in IDLE"
  • Alex V
    Alex V about 11 years
    @andsoa You will also have the same problem if you run the code via the interactive interpreter.