Python线程名称不会出现在ps或htop上

时间:2015-12-18 17:35:22

标签: python multithreading htop

当我为Python线程设置名称时,它不会显示在htop或ps上。 ps输出仅显示python作为线程名称。有没有办法设置一个线程名称,以便它显示在像他们这样的系统报告上?

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}输出

  PID  SPID TTY          TIME CMD
31420 31420 pts/30   00:00:00 python
31420 31421 pts/30   00:00:00 python

4 个答案:

答案 0 :(得分:16)

首先安装prctl module。 (在debian / ubuntu上输入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()

打印

$ 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

答案 1 :(得分:6)

如果系统中安装了prctl,我使用以下猴子补丁将python Thread的名称传播到系统:

try:
    import prctl
    def set_thread_name(name): prctl.set_name(name)

    def _thread_name_hack(self):
        set_thread_name(self.name)
        threading.Thread.__bootstrap_original__(self)

    threading.Thread.__bootstrap_original__ = threading.Thread._Thread__bootstrap
    threading.Thread._Thread__bootstrap = _thread_name_hack
except ImportError:
    log('WARN: prctl module is not installed. You will not be able to see thread names')
    def set_thread_name(name): pass

执行此代码后,您可以照常设置线程的名称:

threading.Thread(target=some_target, name='Change monitor', ...)

这意味着,如果您已经为线程设置了名称,则无需进行任何更改。我不能保证,这是100%安全的,但它对我有用。

答案 2 :(得分:4)

Prctl模块很不错,提供了许多功能,但是取决于libcap-dev软件包。 Libcap2很可能已安装,因为它是许多软件包(例如systemd)的依赖项。因此,如果只需要设置线程名,请在ctypes上使用libcap2。

请参阅下面的改进的悲伤解答。

LIB = 'libcap.so.2'
try:
    libcap = ctypes.CDLL(LIB)
except OSError:
    print(
        'Library {} not found. Unable to set thread name.'.format(LIB)
    )
else:
    def _name_hack(self):
        # PR_SET_NAME = 15
        libcap.prctl(15, self.name.encode())
        threading.Thread._bootstrap_original(self)

    threading.Thread._bootstrap_original = threading.Thread._bootstrap
    threading.Thread._bootstrap = _name_hack

答案 3 :(得分:0)

另一种解决方案(实际上是一种肮脏的解决方案,因为它设置了进程名称,而不是线程名称)是使用pypi的setproctitle模块。

您可以使用pip install setproctitle安装它,并按以下方式使用它:

import setproctitle
import threading
import time

def a_loop():
    setproctitle.setproctitle(threading.currentThread().name)
    # you can otherwise explicitly declare the name:
    # setproctitle.setproctitle("A loop")
    while True:
        print("Looping")
        time.sleep(99)

t = threading.Thread(target=a_loop, name="ExampleLoopThread")
t.start()
相关问题