Nyxynyx
Nyxynyx

Reputation: 63619

Unable to kill process started by Python

After start.exe is executed by Python, the output of start.exe is displayed in the python stdout. However 5 seconds later, we do not see Quitting printed and the task is not killed.

Is there an easier way to terminate an exe that was originally started by Python? Like getting a handle for the exe executed and using that handle to kill the process.

import subprocess
import os
import time

subprocess.call(['.\\start.exe'])

time.sleep(5)
print("Quitting")
os.system("taskkill /im start.exe")

Upvotes: 0

Views: 340

Answers (2)

Gerrat
Gerrat

Reputation: 29690

The reason is that subprocess.call will wait for your start.exe to complete before continuing your script.

You can get a popen object (with better functionality) to your process via:

import subprocess
import os
import time

process = subprocess.Popen(['.\\start.exe'])

time.sleep(5)   
print("Quitting")
process.terminate()

Upvotes: 0

Rui Silva
Rui Silva

Reputation: 338

As you can see at the subprocess documentation, the call function blocks until the process completes.

I believe that you should use the Popen functions as it doesn't block, and provides you a process handle. Then, you can kill it like this: p.kill(), where p is the result from the Popen function.

Upvotes: 1

Related Questions