Python线程名称未显示在ps或htop上 [英] Python thread name doesn't show up on ps or htop

查看:268
本文介绍了Python线程名称未显示在ps或htop上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我为Python线程设置名称时,它不会显示在htop或ps上. ps输出仅显示python作为线程名称.有什么方法可以设置线程名称,使其显示在类似它们的系统报告上?

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

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

推荐答案

首先安装 prctl模块. (在debian/ubuntu上,只需键入sudo apt-get install python-prctl)

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()

此打印

$ 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

这篇关于Python线程名称未显示在ps或htop上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆