Br0k3nS0u1
Br0k3nS0u1

Reputation: 73

How can I run processes in Python?

I searched some examples in the official python page, others pages and also books, but processes doesn't work. In this example I only print a message that is passed as a parameter to each function. I don't know why, but processes don't work in Windows because I tried in 3 different computers(2 with Windows and other with Linux) and a web page to program with Python and process don't work in Windows

from multiprocessing import Process
from time import sleep

def worker(msg):
    
    for i in range(0, 10):
        
        print(msg, end='', flush=True) # <----- print msg

print('Starting')

t2 = Process(target=worker, args=('A',))
t3 = Process(target=worker, args=('B',))
t4 = Process(target=worker, args=('C',))

t2.start() # <---------------------------
t3.start() # <----- they don't work -----
t4.start() # <---------------------------

t2.join()
t3.join()
t4.join()

print('Done')

This is printed as output:

Starting

Done

Upvotes: 0

Views: 88

Answers (2)

Br0k3nS0u1
Br0k3nS0u1

Reputation: 73

Thank to you guys I could solve this.

The error was due to that I didn't use if __name__ == "__main__":, but other error is that I used eclipse with pydev, I don't know why, but I can't do it with eclipse and pydev (I think is limited) until I tried it in sublime text 3 and pycharm.

Upvotes: 0

AKX
AKX

Reputation: 169032

You're not waiting for the child processes to stop; once the parent program ends, they're killed.

Add

t2.join()
t3.join()
t4.join()

after your print('Done') to give them a chance to do their thing.

Also, args must be a tuple of arguments, not a single string.

Upvotes: 2

Related Questions