Ehsan
Ehsan

Reputation: 83

Contents are not printed using Multiprocessing in Python

I just want to run an example from this site which is the following code:

from multiprocessing import Process


def square(x):

    for x in numbers:
        print('%s squared  is  %s' % (x, x**2))

if __name__ == '__main__':
        numbers = [43, 50, 5, 98, 34, 35]

    p = Process(target=square, args=('x',))
    p.start()
    p.join()
    print ("Done")
 

it says that if you run the code, you should see the following results:

#result
Done
43 squared  is  1849
50 squared  is  2500
5 squared  is  25
98 squared  is  9604
34 squared  is  1156
35 squared  is  1225

But as I run this code, I just see Done in results and nothing more. In that Tutorial used Python 2.7 but I have 3.6 and I added () in prints.

Thank you for your help

Upvotes: 0

Views: 705

Answers (2)

Ethan
Ethan

Reputation: 180

If IDLE quits with no message, and it was not started from a console, try starting from a console (python -m idlelib) and see if a message appears. For example if your python file is in the Desktop you may write

C:\Users\MyName> Desktop\python-file-name -m idlelib

prss win + x and choose command prompt.

Upvotes: 0

Jacques Gaudin
Jacques Gaudin

Reputation: 16958

There are a few problems with your snippet.

  1. Identation: if __name__ == '__main__': is part of the square function
  2. The functionsquare should take the argument numbers not x
  3. The arguments passed to the process should be args=(numbers,)

Once you fix all this, you get:

from multiprocessing import Process


def square(numbers):

    for x in numbers:
        print('%s squared  is  %s' % (x, x**2))

if __name__ == '__main__':
    numbers = [43, 50, 5, 98, 34, 35]

    p = Process(target=square, args=(numbers,))
    p.start()
    p.join()
    print ("Done")

which runs correctly.

If you use IDLE on Windows, to see the output, you need to start IDLE from the command line:

C:\Users\MyName>python -m idlelib

as explained in this question

Upvotes: 2

Related Questions