5
0

【Python】【小ネタ】WindowsのプロセスIDが生存しているか確認する方法

Last updated at Posted at 2023-12-10

前提

プロセスIDの変数pidにはintの他Noneがアサインされることもある。
Noneの場合は既にプロセスがkillされていると判断してFalseを返すことにする。
それ以外では、プロセスIDをなんらかの方法で用いて生存を判断する。

標準ライブラリsubprocessを使う場合

import subprocess


def exists_task(pid: "int | None") -> bool:
    if pid is None:
        return False
    proc = subprocess.run(
        # chcp437指定でコマンドの言語を英語に切り替える。
        # これで実行環境が日本語でも`stdout`は英語バイト列になる
        ["chcp", "437", "|", "tasklist", "/fi", f"PID eq {pid}"],
        stdout=subprocess.PIPE,
        shell=True,
        # エンコードを指定すると`UnicodeDecodeError`が発生する時がある
    )
    # 判断基準はバイト列の比較でこと足りる
    return b"INFO: No tasks are running which match the specified criteria" not in proc.stdout

comtypesを使う場合

import comtypes.client


# Microsoft WMI Scriptingのモジュール作成
comtypes.client.GetModule("wbemdisp.TLB")
# WbemScriptingを静的import
# `WbemScripting = comtypes.client.GetModule(...)`でも実行時に動く(IDEによる静的解析はできない)
from comtypes.gen import WbemScripting


def exists_task(pid: "int | None") -> bool:
    if pid is None:
        return False


    wmi = comtypes.client.CreateObject(WbemScripting.SWbemLocator, interface=WbemScripting.ISWbemLocator)
    wmi_service = wmi.ConnectServer(".", "root\\cimv2")
    result = wmi_service.ExecQuery(f"SELECT * FROM Win32_Process WHERE ProcessId = {pid}")
    return bool(result.Count)

5
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
5
0