简体   繁体   中英

How to kill a subprocess in python

I have code which runs a webcamera on a linux pc using the gst-launch command.

When I kill the process, the webcamera window does not turn off, but the program stops running. I want the webcamera window also to be closed. Can you help me on this?

import subprocess
import time
import os
import signal

cmd = "gst-launch-1.0 -v v4l2src ! video/x-raw,format=YUY2 ! videoconvert ! autovideosink"
process = subprocess.Popen(cmd, shell = True)
time.sleep(5)
#print(subprocess.Popen.pid)
#process.terminate()
os.kill(process.pid, signal.SIGKILL)
#process.kill()

Hope it will help you.

import os
import signal
import subprocess

process = subprocess.Popen(cmd, shell = True)
os.killpg(os.getpgid(process.pid), signal.SIGTERM)

For me, the currently accepted answer will terminate the main program as well. If you experience the same problem and want it to continue, you will have to also add the argument preexec_fn=os.setsid to popen. So in total:

import os
import signal
import subprocess

process = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid)
os.killpg(os.getpgid(process.pid), signal.SIGTERM)

I got this from here: https://stackoverflow.com/a/4791612/11642492

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