知道进程是否还在 运行 他的命令行,在 python

Know if a processus still running with his command line, in python

我有进程的命令,我想知道它是否仍然 运行 python。

我有命令行“java -Xms2000M ... nogui”

它是 cmd 的子进程 windows。

问题是:我不知道该怎么做, 我读了一些关于 subprocess 模块和 popen 的东西,但是如果有人愿意启发我

谢谢。

您可以使用 wmic 查询所有 运行 Windows 进程,将其包装在子进程调用中并根据您的需要过滤所有进程(java.exespigot-):

import subprocess

def isProcessRunning(appName, argPattern):
    command = 'wmic process get Caption,Processid,Commandline /format:csv'
    cmd = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=False)
    stdout, stderr = cmd.communicate()
    if cmd.returncode == 0:
        for line in stdout.decode('utf-8').split('\n'):
            line = line.lower().strip()
            
            if not line:
                continue

            if appName in line and argPattern in line:
                print("Found:")
                print(line)
                return True

print(isProcessRunning('spotify.exe', 'renderer'))

输出:

Found:
vm-pc_win7,spotify.exe,"c:\users\f3k\appdata\roaming\spotify\spotify.exe" --type=renderer ... --product-version=spotify/1.1.43.700 --disable-spell-checking --device-scale-factor=1 --num-raster-threads=1 --renderer-client-id=4 --mojo-platform-channel-handle=2268 /prefetch:1,5148
True

注:
wmic returns CSV 格式,我只是要搜索整个字符串。