Matty G
Matty G

Reputation: 25

Subprocess management - Killing a subprocess

I have been trying to make a python script that will play on Mac OS X and I have gotten it to work with a .py script in Terminal, but I can't stop it. I have been trying for weeks, os.kill(), process.terminate(), everything I could find on other StackOverflow questions. Here is my code, can anyone tell me the proper way to terminate this sub-process? (I believe I am using python 2.7)

import time
import subprocess

subprocess.call(["afplay", "/Users/0095226/Desktop/introsong.wav"])
time.sleep(4)
(WHATEVER KILLS IT HERE PLEASE)

Upvotes: 0

Views: 968

Answers (1)

jermenkoo
jermenkoo

Reputation: 653

You need to use subprocess.Popen() as you can assign the process handle to a variable and later kill it.

import time
import subprocess

p = subprocess.Popen(["calc"])
time.sleep(4)
p.kill()

The other method is to use os.kill() along with signal.SIGINT to kill the process, as seen here:

import time
import signal
import subprocess
import os

p = subprocess.Popen(["calc"])
time.sleep(4)
os.kill(p.pid, signal.SIGINT)

We are able to access the PID (Process ID) and therefore we can kill it using os.kill(). signal is the module which contains codes for how to kill the process, e.g. send it the abort (SIGABRT), interrupt (SIGINT) etc.

Upvotes: 2

Related Questions