michal
michal

Reputation: 327

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)

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.

I am unable to kill process by PID because it keeps changing. The only other option is to kill camera.py by its name, but it doesn't work.

main script:

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

this is my camera.py script:

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

Can anyone help please? thanks

Upvotes: 0

Views: 1432

Answers (3)

Headhunter Xamd
Headhunter Xamd

Reputation: 606

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. This gives you access to the Popen object of the calls.

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.

This should actually be done through an shutdown sequence. You should never Force close applications if you can let it close itself.

Upvotes: 0

Mehdi Yedes
Mehdi Yedes

Reputation: 2375

Use pkill:

$ sudo pkill -f camera.py 

Upvotes: 2

Rolf of Saxony
Rolf of Saxony

Reputation: 22443

If you make camera.py executable, put it on your $PATH and make line 1 of the script #!/usr/bin/python, then execute camera.py without the python command in front of it, your "sudo killall camera.py" command should work.

Upvotes: 1

Related Questions