进程名称是从 Python 设置的,但从外部看不到



我有一个复杂的多处理Python项目,它启动了大约8-10个进程。这些进程获得不同的唯一名称,这些名称在代码中工作正常。但是,如果我检查终端中正在运行的进程,这些进程没有唯一的名称。它们与父级的名称相同(实际上是命令行本身(。

使用环境:

  • 蟒蛇 3.6.6
  • 红帽 Linux 7
  • XFCE4 终端 0.8.7.4

最小代码:

import multiprocessing
import time

def sleeping_function(s_time):
multiprocessing.current_process().name = "process_{}".format(s_time)
print(multiprocessing.current_process().name)
time.sleep(s_time)

if __name__ == "__main__":
times = [200, 201, 202, 203, 204]
with multiprocessing.Pool(processes=len(times)) as pool:
results = pool.map(sleeping_function, times)

输出:

>>> python3 test.py
process_200
process_201
process_202
process_203
process_204

检查我的终端中正在运行的进程(而所有进程都在脚本中运行(。

命令:

ps  aux -u my_user_name | grep python

输出:

my_user_name 888273  0.1  0.0 359804 11288 pts/162  Sl+  15:10   0:00 python3 test.py
my_user_name 888274  0.0  0.0 138608  8040 pts/162  S+   15:10   0:00 python3 test.py
my_user_name 888275  0.0  0.0 138608  8056 pts/162  S+   15:10   0:00 python3 test.py
my_user_name 888276  0.0  0.0 138608  8056 pts/162  S+   15:10   0:00 python3 test.py
my_user_name 888277  0.0  0.0 138608  8060 pts/162  S+   15:10   0:00 python3 test.py
my_user_name 888278  0.0  0.0 138608  8060 pts/162  S+   15:10   0:00 python3 test.py

我想看到process_20X进程名称,而不是调用的 Python 命令。

我的问题:

是否可以为外部可见的 Python 脚本中的进程提供唯一名称(例如:从终端(?

您可以使用 setproctitle 模块来更改进程的系统名称。显然,模块调用具有相同名称的 C 例程。

setproctitle.setproctitle(multiprocessing.current_process().name)

它在 Ubuntu 上对我有用。

最新更新