python multiprocessing - access the process name inside the function called with Process.start(target=func)
Solution 1
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
Solution 2
Instead of passing target
argument, override the run
method. From there, you can invoke someFunc
and pass the process object to it.
The name is not an OS level concept. It is Python level and it is not automatic that the process you execute in even has a Process
object anywhere.
Anuvrat Parashar
Programmer biased towards Linux, Python, FOSS etc.
Updated on June 05, 2022Comments
-
Anuvrat Parashar about 2 years
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
?