Monitoring a subprocess created from the command line in windows

I open a program using subprocess.Popen

import subprocess

prog = subprocess.Popen(['myprog', args], shell=True)

I want to track the "myprog" process and wait until it completes before my code.

The problem I ran into is prog.pid - this is the shell PID, not "myprog", and I don't know how to get the "myprog" PID. I tried using psutil to find prog.pid child processes:

parent = psutil.Process(prog.pid)
children = parent.children(recursive=True)

but an empty list is returned.

Unfortunately, I cannot run 'myprog' without a shell. When I run the command using shell=False , the following error message appears: FileNotFoundError: [WinError 2] The system cannot find the file specified

I have a high and low level web search, but all the promising links for non-Windows users.

+5
source share
1 answer

Your atom command is probably a .cmd file that runs the executable, which explains the need for shell=True

You will not go on to re-encode the .bat file extension in python, BUT you also don't need an executable PID.

If the executable ends, the batch file ends, so forget about monitoring prog.pid , just view the prog with poll (in the same python script, of course).

The poll method allows you to check whether the process has completed (if there is one, it returns an exit code if it does not return None ) and this does not block, so you can do this at any time:

 if prog.poll() is not None: # process has ended print("ended") 

We remind you about blocking the wait for this:

 return_code = prog.wait() 

But in your case, the atom.cmd command seems to start the process in the background, which makes monitoring impossible without a PID.

The workaround in this case is to make a copy of atom.cmd , remove the start prefix to run the executable in the foreground, and instead start the copy.

(or since cmd calls another atom.cmd file when commenting, find the file app-1.13.0\resources\cli\atom.cmd from atom.cmd source directory and remove the start prefix there)

+1
source

Source: https://habr.com/ru/post/1263283/


All Articles