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
  • 667
  • 1
  • 14
  • 41

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
  • 260,549
  • 28
  • 431
  • 505
2

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
  • 767
  • 5
  • 15
1

I figured that killing the process was the easiest:

os.system("taskkill /f /im ssf.exe")
vdvaxel
  • 667
  • 1
  • 14
  • 41