17

I would like to set the title of a thread (the title seen in ps or top)in Python in order to make it visible to process tracer programs. All the threads of a process are always called python or called file name when /usr/bin/python is used and the script is called via ./script.

Now, I want to change each thread's name. I have a simple script with 4 threads (incl main thread). I use threading to start the threads.

Is there a way that I could achieve this without having to install third-party stuff? Any guidance is appreciated.

Guy Avraham
  • 3,482
  • 3
  • 38
  • 50
mozcelikors
  • 2,582
  • 8
  • 43
  • 77

2 Answers2

19

Try this:

def your_function(arg1, arg2, argn):
    * do stuff *


new_thread = threading.Thread(target=your_function, args=(arg1, arg2, argn))
new_thread.name = 'your name'
new.thread.start()

Where new_thread.name is your answer.

Nicolas Iceberg
  • 665
  • 1
  • 6
  • 17
  • Trying to reconcile with https://stackoverflow.com/questions/34361035/python-thread-name-doesnt-show-up-on-ps-or-htop – matanster May 19 '20 at 19:20
2

Just do the following: t = threading.Thread(name='my_thread')

Guy Avraham
  • 3,482
  • 3
  • 38
  • 50
Tomer
  • 1,058
  • 11
  • 18
  • 2
    Nope, that didn't work, check the link in the comments, pactl must be used in order to register the name to linux process list. – mozcelikors Sep 27 '18 at 11:05
  • You probably mean [this](https://stackoverflow.com/questions/34361035/python-thread-name-doesnt-show-up-on-ps-or-htop) – matanster May 19 '20 at 19:27
  • Why the above answer has 17 likes where as this has -2 ? Even though both answers didnt address the actual question – Bhanu Tez Mar 11 '22 at 06:49