简体   繁体   中英

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)

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, eg send it the abort (SIGABRT), interrupt (SIGINT) etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM