Search code examples
pythontaskkill

after window close program.exe file still running in background


I have a script that runs a program.exe in the background. How to close a program from the background in task manager after closing the command window script

script

command = [
        "program.exe",
        "-i",
        "-o",
    ]


    process = subprocess.Popen(
        command,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        bufsize=1,
        universal_newlines=True,
    )
    stdout, stderr = process.communicate()

print(command)

Solution

  • Subprocess popen creates an separate process that will consiste after your script exectuded an ended. So to end that proces you should explicitly command it to end.

    process.terminate()
    

    will gracefully shut it down while

    process.kill()
    

    can force kill it.

    You can use process.poll() to check if it still runs so you can better do

    process.terminate()
    time.sleep(1)
    if process.poll() is None:
        process.kill()
    

    This tells program to cleanly close but if it doesnt close you can kill after waiting