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?
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 bash script are REMed out as I could get neither of them to work... the script was still running after the python script ended. I apologize for this sloppiness, I'm pretty new to python programming.

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 script
subprocess.Popen(['/bin/bash', './'])

#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 script to stop taking pictures (didn't work)
#for proc in psutil.process_iter():
    # check whether the process name matches
#    if == PROCNAME:
#        proc.kill()

#this kills the 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 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
What about
proc = subprocess.Popen(['/bin/bash', './'])
# do things
That is what I was attempting to do with this...
import psutil
# this kills the script to stop taking pictures (didn't work)
for proc in psutil.process_iter():
    # check whether the process name matches
    if == PROCNAME:
But it did not work. The 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 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.


Thank you!

That did the trick!

Simple, elegant, awesome! Big Grin
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])

os.kill(pid, True)
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
Gaming Collection
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. ;-)

Possibly Related Threads…
Thread Author Replies Views Last Post
  python keeps opening script directory Tyrel 2 160 Jul-27-2021, 08:37 PM
Last Post: Tyrel
  Using import in python script offline - HELP!! blackhatter1001001 1 184 Jul-25-2021, 05:57 AM
Last Post: ndc85430
  how to loop a script? ZYSIA 1 234 Jul-22-2021, 06:46 AM
Last Post: Gribouillis
  string function doesn't work in script ClockPillow 3 305 Jul-13-2021, 02:47 PM
Last Post: deanhystad
  Encountering `importlib_metadata.PackageNotFoundError` trying to run console script gretchenfrage 0 135 Jul-08-2021, 09:26 PM
Last Post: gretchenfrage
  [split] Help- converting file with pyton script eltomassito 6 447 Jul-02-2021, 05:29 PM
Last Post: snippsat
  Py script that triggers ever 3 hours, but only between 9:15 am to 3:30 pm, Mon to Fri Pymod 2 241 Jun-30-2021, 05:14 PM
Last Post: Larz60+
  script with imports works but pytest gives "ModuleNotFoundError"? Hpao 0 220 Jun-27-2021, 08:30 PM
Last Post: Hpao
  How can I get Python Bulk Email Verification Script With API? zainalee 1 350 Jun-06-2021, 09:19 AM
Last Post: snippsat
  Python script for excel sheet Nabil 5 483 Jun-01-2021, 02:29 PM
Last Post: anuradha

Forum Jump:

User Panel Messages

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