Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python multiprocessing - access the process name inside the function called with Process.start(target=func)

I am playing around with python multiprocessing module and wanted to be able to display the name of the currently executing process.

If I create a custom MyProcess class inheriting from multiprocessing.Process I can print the process's name in the following way

from multiprocessing import Process

class MyProcess(Process):
   def __init__(self):
        Process.__init__(self)

   def run(self):
        #do something nasty and print the name
        print self.name

p = MyProcess()
p.start()

However if I am creating processes using the constructor of Process class

from multiprocessing import Process
def somefunc():
    print Process.name                 #1

p = Process(target=somefunc)
p.start()
print p.name                           #2

#2 works but #1 doesn't. Is there a way I could print the name of the currently executing process inside somefunc?

like image 395
Anuvrat Parashar Avatar asked Jul 18 '12 07:07

Anuvrat Parashar


1 Answers

You can use the current_process function:

from multiprocessing import Process, current_process

def somefunc():
    print current_process().name

if __name__ == '__main__':
    p = Process(target=somefunc)
    p.start()
    print p.name
like image 127
schlamar Avatar answered Sep 21 '22 21:09

schlamar