简体   繁体   English

python通过名称而不是PID杀死script.py

[英]python kill script.py by name not PID

one script starts automatically when my raspberry is booted up, within this script there is motion sensor, if detected, it starts a subproces camera.py (recording a video, then converts the video and emails) 一个脚本在我的树莓启动时自动启动,该脚本中有运动传感器,如果检测到,它将启动子过程camera.py(录制视频,然后转换视频和电子邮件)

within the main script that starts u on booting up, there is another if statement, if button pressed then stop the camera.py and everything in it and do something else. 在启动u的主脚本中,还有另一个if语句,如果按下了按钮,则停止camera.py及其中的所有内容,然后执行其他操作。

I am unable to kill process by PID because it keeps changing. 我无法通过PID终止进程,因为它一直在变化。 The only other option is to kill camera.py by its name, but it doesn't work. 唯一的其他选择是通过其名称杀死camera.py,但这不起作用。

main script: 主要脚本:

p1 = subprocess.Popen("sudo python /home/pi/camera.py", shell=True)

this is my camera.py script: 这是我的camera.py脚本:

import os
os.system("raspivid -n -o /home/pi/viseo.h264 -t 10000")
os.system(.... python script0.py
os.system(.... python script1.py

i can do: 我可以:

os.system("sudo killall raspivid")

if i try 如果我尝试

os.system("sudo killall camera.py")

it gives me a message: No process found 它给我一条消息:找不到进程

this only stops the recording but i also want to kill every other script within camera.py 这只会停止录制,但我也想杀死camera.py中的所有其他脚本

Can anyone help please? 有人可以帮忙吗? thanks 谢谢

使用pkill

$ sudo pkill -f camera.py 

如果您将camera.py设为可执行文件,请将其放在$ PATH上,并使脚本#!/usr/bin/python 1行生效,然后在不带python命令的情况下执行camera.py,即"sudo killall camera.py"命令应该可以正常工作。

instead of using: 而不是使用:

import os
os.system("raspivid -n -o /home/pi/viseo.h264 -t 10000")
os.system(.... python script0.py)
os.system(.... python script1.py)

you should use the same Popen structure as how you spawn this process. 您应该使用与生成此过程相同的Popen结构。 This gives you access to the Popen object of the calls. 这使您可以访问调用的Popen对象。

import os 
pvid = subprocess.Popen("raspivid -n -o /home/pi/viseo.h264 -t 10000")
p1 = subprocess.Popen(.... python script0.py)
p2 = subprocess.Popen(.... python script1.py)

Then you can get the pid of all the different scripts and kill them through that. 然后,您可以获取所有不同脚本的pid,并通过它们杀死它们。

This should actually be done through an shutdown sequence. 这实际上应该通过关闭顺序来完成。 You should never Force close applications if you can let it close itself. 如果可以自行关闭应用程序,则决不要强行关闭应用程序。

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

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