How do I know which python script is running in taskmgr?

python, taskmanager, windows

Solution

The usual answer to such questions is Process Explorer. You can see the full command line for any instance of `python.exe` or `pythonw.exe` in the tooltip.

To get the same information in Python, you can use the psutil module.

import psutil

pythons = [[" ".join(p.cmdline), p.pid] for p in psutil.process_iter() 
            if p.name.lower() in ("python.exe", "pythonw.exe")]

The result, `pythons`, is a list of lists representing Python processes. The first item of each list is the command line that started the process, including any options. The second item is the process ID.

The psutil `Process` class has a lot of other stuff in it so if you want all that, you can do this instead:

pythons = [p for p in psutil.process_iter() if p.name.lower() in ("python.exe", "pythonw.exe")]

Now, on my system, iterating all processes with `psutil.process_iter()` takes several seconds, which seems to me ludicrous. The below is significantly faster, as it does the process filtering before Python sees it, but it relies on the `wmic` command line tool, which not all versions of Windows have (XP Home lacks it, notably). The result here is the same as the first `psutil` version (a list of lists, each containing the command line and process ID for one Python process).

import subprocess

wmic_cmd = """wmic process where "name='python.exe' or name='pythonw.exe'" get commandline,processid"""
wmic_prc = subprocess.Popen(wmic_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
wmic_out, wmic_err = wmic_prc.communicate()
pythons = [item.rsplit(None, 1) for item in wmic_out.splitlines() if item][1:]
pythons = [[cmdline, int(pid)] for [cmdline, pid] in pythons]

If `wmic` is not available, you will get an empty list `[]`. Since you know there's at least one Python process (yours!), you can trap this as an error and display an appropriate message.

To get your own process ID, so you can exclude it from consideration if you're going to e.g. start killing processes, try pywin32's `win32process.GetCurrentProcessID()`

Problem

It seems that in the task manager all I get is the process of the python/pythonwin. So How can I figure out which python script is running?

Original source