0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python の psutil でプロセスの情報を取得

0
Posted at

やりたいこと

Python で psutil を使ってプロセスの情報を取得する。

  • 特定のプロセスの状態を取得
  • 特定のコマンドのプロセスを特定

特定のプロセスの状態を取得

psutil.Process(プロセスID) で指定のプロセスIDのプロセスの情報を取得することができる。

import json
import psutil

proc = psutil.Process(11590)
print(proc)
print()
print(json.dumps(proc.cmdline(), indent=2))

実行結果例は以下の通り。

psutil.Process(pid=11590, name='celery', status='sleeping')
[
  "/home/xxx/.pyenv/versions/3.12.5/bin/python3.12",
  "/home/xxx/.pyenv/versions/3.12.5/bin/celery",
  "-A",
  "celery_app",
  "worker",
  "-Q",
  "task"
]

特定のコマンドのプロセスIDを取得

psutil.process_iter() で各プロセスの情報を参照することができる。
以下では python の celery で 'celery_app' を実行しているプロセスのプロセスIDを取得している。

import re
import psutil

def get_celery_process_ids(program):
    process_ids = []

    for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
        items = proc.info.get('cmdline')
        # print(items)

        for item in items:
            try:
                if not re.match('(?:^|.*/)python(?:[0-9]+)[.](?:[0-9]+)$', items[0]):
                    break
                if not re.match('(?:^|.*/)celery$', items[1]):
                    break
                if items[2] != '-A':
                    break
                if items[3] != program:
                    break

                process_ids.append(proc.pid)
                break

            except Exception as e:
                pass

    return process_ids

pids = get_celery_process_ids('celery_app')
print(pids)

実行結果例は以下の通り。

[11541, 11590]
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?