简体   繁体   English

如何杀死 python 中的子进程

[英]How to kill a subprocess in python

I have code which runs a webcamera on a linux pc using the gst-launch command.我有使用gst-launch命令在 linux pc 上运行网络摄像头的代码。

When I kill the process, the webcamera window does not turn off, but the program stops running.当我终止进程时,网络摄像头 window 没有关闭,但程序停止运行。 I want the webcamera window also to be closed.我希望网络摄像头 window 也被关闭。 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.如果您遇到同样的问题并希望它继续,您还必须将参数preexec_fn=os.setsid添加到 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我从这里得到这个: https://stackoverflow.com/a/4791612/11642492

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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