Bottom Page

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
Quote
#2
What about
proc = subprocess.Popen(['/bin/bash', './timelapse.sh'])
....
# do things
...
proc.kill()
Quote
#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
Quote
#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
Johnny's CookBook - Powered By: Python3.8 | Bootstrap4 | Apache2 | Django
Quote
#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. ;-)
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Execute full script samuelbachorik 0 70 Aug-06-2020, 08:09 PM
Last Post: samuelbachorik
  How to run diskpart from python script obgocs 1 76 Aug-06-2020, 05:46 AM
Last Post: Gribouillis
  Learning Python with telnetlib. Script seems to stall John_Williamson 1 121 Jul-23-2020, 05:52 PM
Last Post: John_Williamson
  The script won't take voice input ShishirModi 2 98 Jul-21-2020, 05:56 AM
Last Post: ShishirModi
  run a health check script on cloud server through paramiko amritjsr 4 186 Jul-21-2020, 02:30 AM
Last Post: amritjsr
  How to create a Kibana Visualisation with python script? adzadz 0 88 Jul-20-2020, 06:41 AM
Last Post: adzadz
  Need help creating a simple script Nonameface 12 359 Jul-14-2020, 02:10 PM
Last Post: BitPythoner
  Run script on startup in Debian with systemd? MrGlasspoole 5 332 Jul-12-2020, 11:48 AM
Last Post: MrGlasspoole
  Python 3.6.10 fails when running a localized script. Mikee 2 184 Jul-09-2020, 10:25 PM
Last Post: Mikee
  Python: Automated Script to Read Multiple Files in Respective Matrices Robotguy 7 391 Jul-03-2020, 01:34 AM
Last Post: bowlofred

Forum Jump:


Users browsing this thread: 1 Guest(s)