I want Python to get the executable path from the process ID.

Asked 2 years ago, Updated 2 years ago, 72 views

Thank you for your help.

I want Python to get the path of the executable from the process ID.
The process ID must have been obtained in some way.
So, as far as I've looked into it, it seems that it can be easily implemented using psutil, but I don't think there's any other way to add psutil just for that reason.
If you can use Win32 API, could you tell me how to do that?
The environment is Windows 10, Python 3.7.5.

Thank you for your cooperation.

python python3 windows

2022-09-30 21:45

2 Answers

Thank you for your help.
In the end, in this case, I knew the process handle, so I was able to get it from ctypes.
Thank you for your advice in the comments and answers.
I will post a sample just in case.

from ctypes import*

defaultExeFileName(processHandle):
    exeFileName=create_unicode_buffer(wintypes.MAX_PATH)
    length=wintypes.DWORD (wintypes.MAX_PATH)
    if windll.Kernel32.QueryFullProcessImageNameW(processHandle,0,exeFileName,byref(length)):
        returnFileName.value
    else:
        return None


2022-09-30 21:45

I actually tried to move the cord using wmic.
It's a feeling, but it's pretty fast.I didn't expect it.
Since the wmic command is launched, it is undeniable that heavy use puts a load on the system, but I think there is no problem for single use.

import subprocess
pid = 16252
cmd = "wmic process where (ProcessId="+str(pid)+") get ExecutablePath/format:CSV"
result=subprocess.check_output(cmd, shell=True)
print(result.decode(encoding='shiftjis'))
Node, ExecutablePath


XXXX, C:\Program Files (x86)\Digital Clock\Digital Clock.exe

XXXX is the computer name.I'm lying down.

Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64bit (AMD64)] on win32


2022-09-30 21:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.