0

I am trying to start a .exe from a Python program, let it run for a couple of seconds and then kill it. I'm using the subprocess library. Here's what I did (in short):

import subprocess

p = subprocess.Popen('start /b .\ssf.exe', shell=True)
time.sleep(5)
p.terminate()

I also tried p.kill(), but without any luck.

Also, when I print(p.pid), it's a different PID than the one I find in the processes list... Can someone tell me why this is not working?

vdvaxel
  • 617
  • 1
  • 11
  • 37

3 Answers3

4

You didn't start ssf.exe in a subprocess. You started a subprocess that would start ssf.exe in yet another process. When you run p.terminate(), you're terminating the middleman, not ssf.exe.

user2357112
  • 235,058
  • 25
  • 372
  • 444
1

Try this:

import os
import signal
import subprocess

p = subprocess.Popen('start /b .\ssf.exe', shell=True, preexec_fn=os.setsid)
time.sleep(5)
os.killpg(os.getpgid(p.pid), signal.SIGTERM) 
arunp9294
  • 727
  • 4
  • 14
1

I figured that killing the process was the easiest:

os.system("taskkill /f /im ssf.exe")
vdvaxel
  • 617
  • 1
  • 11
  • 37