gpt4 book ai didi

python - Python线程名称未显示在ps或htop上

转载 作者:行者123 更新时间:2023-12-03 13:07:40 27 4
gpt4 key购买 nike

当我为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

最佳答案

首先安装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

关于python - Python线程名称未显示在ps或htop上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57711773/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com