Search code examples
pythonsubprocesspopen

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


I have the command of a processus, and i want know if it still running with python.

enter image description here

I have the command line "java -Xms2000M ... nogui"

it's a sub process of a cmd windows.

the problem is: i don't know how to do that, I read something about subprocess module and popen, but If someone would like to enlighten me

thank you .


Solution

  • You could use wmic to query all running Windows processes, wrapping that in a subprocess call and filter all processes by your needs (java.exe, spigot-):

    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'))
    

    Out:

    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
    

    Note:
    wmic returns a CSV format, I am just going to search the whole string.