Python3でプロセスIDからプロセス名を取得する(WindowsAPI使用)
PythonからGetModuleBaseNameを呼び出し、プロセス名を取得します。 Windows APIを利用しているため、Windowsでしか動作しません。
コード
import ctypes # 引数としてプロセスIDを与え、プロセス名を取得する def get_name_by_pid(pid): PROCESS_ALL_ACCESS = 0x1f0fff hProcess = ctypes.windll.kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, pid) if hProcess == 0: return None buf = ctypes.create_unicode_buffer(1024) ret = ctypes.windll.psapi.GetModuleBaseNameW(hProcess, 0, buf, len(buf)) if ret == 0: return None return buf.value # 使用例 if __name__ == "__main__": name = get_name_by_pid(1234) print(name)