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.
Gaming Collection
Homepage
my-python
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 can I get Python Bulk Email Verification Script With API? zainalee 1 214 Jun-06-2021, 09:19 AM
Last Post: snippsat
  Python script for excel sheet Nabil 5 309 Jun-01-2021, 02:29 PM
Last Post: anuradha
  Automatic user/password entry on prompt by bash script PBOX_XS4_2001 3 339 May-18-2021, 06:42 PM
Last Post: Skaperen
  Possible to execute a python script before log off/shutdown with input commands? Kaltex 1 225 May-18-2021, 06:31 AM
Last Post: Skaperen
  cant use ping, sudo or other commands in remote shell script. throwaway34 7 441 May-17-2021, 11:29 AM
Last Post: throwaway34
  Running script on multiple files Afrodizzyjack 1 237 May-14-2021, 10:49 PM
Last Post: Yoriz
  Run CMD Command In Python Script shantanu97 2 1,036 May-13-2021, 08:08 AM
Last Post: Gribouillis
  Python script in Ubuntu core Nithin_Kumar 1 406 May-11-2021, 01:14 AM
Last Post: Skaperen
  Run one Python Script from Another Script stylingpat 1 268 May-03-2021, 02:59 PM
Last Post: Marbelous
  Get Azure activity logs using python script raham3406 4 334 Apr-27-2021, 05:10 AM
Last Post: raham3406

Forum Jump:

User Panel Messages

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