Python multiprocessing - accessing the process name inside a function called with Process.start (target = func)

I am playing with the python multiprocessing module and want to be able to display the name of the current executable process.

If I create my own class MyProcess, inheriting from multiprocessing. The process I can print the process name as follows.

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 create processes using the constructor of the 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 can print the name of the currently running process inside somefunc ?

+6
source share
2 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 
+8
source

Instead of passing the target argument, override the run method. From there, you can call someFunc and pass it a process object.

The name is not an OS level concept. This is a Python level and it is not automatic that the process you are running even has a Process object anywhere.

+3
source

Source: https://habr.com/ru/post/920777/


All Articles