Python Forum
How to kill a bash script running as root from a python script?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to kill a bash script running as root from a python script?
#1
Not sure if this is the best place to ask this question, but I've been looking all over Stack Exchange and other forums for the past week and still haven't found a working solution for this.

I need to gracefully kill a bash script from inside a python script, and so far I can't make it work.

I am running this on a Raspberry Pi Zero W running the latest version of RasPiOS and Python3.

I am running a python3 script automatically at startup from init.d (it runs as root). In that python script I call a bash script to also start (it also runs as root).
The python script is running a stepper motor, the bash script is running a timelapse series with the Pi camera.
The goal is to create a sunrise to sunset panoramic timelapse video. I need both scripts to run in parallel in order to control frame rates and panning speed independently from each other.
What I'm trying to accomplish is:
On boot, automatically start the motor panning, and start the camera taking pictures.
Once the stepper motor has completed it's pan, then gracefully kill the bash script that is running the camera. (this is what I'm having problems with) Sad
Then have the motor return to it's starting position.
Then shut down the Pi.

Here is the python script I'm using... please note the 2 (of many) solutions I've attempted to use to kill the timelapse.sh bash script are REMed out as I could get neither of them to work... the timelapse.sh script was still running after the python script ended. I apologize for this sloppiness, I'm pretty new to python programming.
#!/usr/bin/python3

from adafruit_motorkit import MotorKit
from adafruit_motor import stepper
from time import sleep
import subprocess
from subprocess import call
#import psutil
#import os, signal

kit = MotorKit()

# this starts the timelapse.sh script
subprocess.Popen(['/bin/bash', './timelapse.sh'])

#this is the slow east to west pan while pics are taken during timelapse using 5V 28BYJ-48 1:64 gear ratio stepper motor
for j in range(22400):
    for i in range(1):
        kit.stepper1.onestep(direction=stepper.FORWARD, style=stepper.MICROSTEP)
#set time between motor steps
    sleep(2.41)   #timing for 270 degree (22400 steps) 15 hour pan with 16 microstepping

# this kills the timelapse.sh script to stop taking pictures (didn't work)
#PROCNAME = "timelapse.sh"
#for proc in psutil.process_iter():
    # check whether the process name matches
#    if proc.name() == PROCNAME:
#        proc.kill()

#this kills the timelapse.sh script to stop taking pictures (didn't work)
#def check_kill_process(timelapse):
#    for line in os.popen("ps ax | grep " + pstring + " | grep -v grep"):
#        fields = line.split()
#        pid = fields[0]
#        os.kill(int(pid), signal.SIGKILL)

#this returns the stepper motor to starting position
for i in range(1400):
   kit.stepper1.onestep(direction=stepper.BACKWARD, style=stepper.DOUBLE)

#this shuts down the pi to wait for next reboot via the wittypi3 power controller
call("sudo nohup shutdown -h now", shell=True)
So far I have everything working except being able to gracefully kill the timelapse.sh script before the Pi shuts down.
I would prefer to do this using the script name rather than using it's PID# if possible... just to keep things simpler?
Any help or suggestions would be appreciated. Like I said, I'm new to python so please be very concise in your answers and examples.
Thank you. Big Grin
Reply
#2
What about
proc = subprocess.Popen(['/bin/bash', './timelapse.sh'])
....
# do things
...
proc.kill()
Reply
#3
That is what I was attempting to do with this...
import psutil
# this kills the timelapse.sh script to stop taking pictures (didn't work)
PROCNAME = "timelapse.sh"
for proc in psutil.process_iter():
    # check whether the process name matches
    if proc.name() == PROCNAME:
        proc.kill()
But it did not work. The timelapse.sh script was still running after the python script ended, and I didn't get any errors letting me know that it failed to end the bash script. The only way I realized that it had failed was because there were still pictures being written to the SD card after the python script ended. And I verified this with "ps aux" and could still see the timelapse.sh process running.
I was thinking maybe because it is running in the background as root? I don't know. It needs to run as root because if I run the scripts as a user, and then SSH into the Pi while everything is running, it will cause the scripts to 'pause' until I end the SSH login session.

Gribouillis

Thank you!

That did the trick!

Simple, elegant, awesome! Big Grin
Reply
#4
This works for me. On linux

#! /usr/bin/env python3
import subprocess
import os

def get_pid(name):
    return subprocess.check_output(['pidof', name])

info = get_pid('bash').split()
pid = int(info[0])
print(pid)

os.kill(pid, True)
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#5
Thanks for the reply menator01... but Gribouillis's suggestion worked perfectly with only 2 lines of code, which is what I was looking for... killing it by using the process name and not having to do the whole lookup of the PID and such. ;-)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to include one script into another? MorningWave 8 304 Mar-21-2024, 10:34 PM
Last Post: MorningWave
  kill python execution program lebossejames 0 182 Mar-16-2024, 11:16 AM
Last Post: lebossejames
  ChromeDriver breaking Python script genericusername12414 1 214 Mar-14-2024, 09:39 AM
Last Post: snippsat
  using PowerShell from Python script for mounting shares tester_V 8 399 Mar-12-2024, 06:26 PM
Last Post: tester_V
  No Internet connection when running a Python script basil_555 8 442 Mar-11-2024, 11:02 AM
Last Post: snippsat
Question Running Python script through Task Scheduler? Winfried 8 335 Mar-10-2024, 07:24 PM
Last Post: Winfried
  Combine console script + GUI (tkinter) dejot 2 360 Feb-27-2024, 04:38 PM
Last Post: deanhystad
  How to receive two passed cmdline parameters and access them inside a Python script? pstein 2 277 Feb-17-2024, 12:29 PM
Last Post: deanhystad
  OBS Script Troubleshooting Jotatochips 0 252 Feb-10-2024, 06:18 PM
Last Post: Jotatochips
  Is possible to run the python command to call python script on linux? cuten222 6 629 Jan-30-2024, 09:05 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020