Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python thread name doesn't show up on ps or htop

When I set the name for a Python thread, it doesn't show up on htop or ps. The ps output only shows python as the thread name. Is there any way to set a thread name so that it shows up on system reports like them?

from threading import Thread import time   def sleeper():     while True:         time.sleep(10)         print "sleeping"  t = Thread(target=sleeper, name="Sleeper01") t.start() t.join() 

ps -T -p {PID} output

  PID  SPID TTY          TIME CMD 31420 31420 pts/30   00:00:00 python 31420 31421 pts/30   00:00:00 python 
like image 348
chamilad Avatar asked Dec 18 '15 17:12

chamilad


People also ask

How do I enable threads in Python?

You need to assign the thread object to a variable and then start it using that varaible: thread1=threading. Thread(target=f) followed by thread1. start() . Then you can do thread1.

How do you sync a Python thread?

The threading module provided with Python includes a simple-to-implement locking mechanism that allows you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock. The acquire(blocking) method of the new lock object is used to force threads to run synchronously.

How do I check thread status in Python?

is_alive() method is an inbuilt method of the Thread class of the threading module in Python. It uses a Thread object, and checks whether that thread is alive or not, ie, it is still running or not. This method returns True before the run() starts until just after the run() method is executed.

Can threads spawn threads Python?

Yes, spawning threads from within another thread is OK. Just remember that there exists a main Python thread, that governs the others.


1 Answers

First install the prctl module. (On debian/ubuntu just type sudo apt-get install python-prctl)

from threading import Thread import time import prctl  def sleeper():     prctl.set_name("sleeping tiger")     while True:         time.sleep(10)         print "sleeping"  t = Thread(target=sleeper, name="Sleeper01") t.start() t.join() 

This prints

$ ps -T   PID  SPID TTY          TIME CMD 22684 22684 pts/29   00:00:00 bash 23302 23302 pts/29   00:00:00 python 23302 23303 pts/29   00:00:00 sleeping tiger 23304 23304 pts/29   00:00:00 ps 

Note: python3 users may wish to use pyprctl.

like image 174
Nick Craig-Wood Avatar answered Sep 19 '22 15:09

Nick Craig-Wood