How to terminate a running python script correctly through bash?

I am having a little bit of a conundrum. Basically I have this kind of setup:

#!/bin/bash

if [ "$1" == "--on" ]; then
    pyhton3 script.py --option a &
    python3 script.py --option b &
elif [ "$1" == "--off" ]; then
   #What do I put here to turn off the python scripts?
fi

I tried something like just pkill python, but that didn’t actually work properly, only closing the terminal that executed the script will close the python scripts properly.

I need to send the equivalent of CTRL+C to the python scripts running in the background, how can I do this?

Try this:

#!/bin/bash

if [ "$1" == "--on" ]; then
    python3 script.py --option a &  # Note: Fixed typo 'pyhton3' to 'python3'
    python3 script.py --option b &
elif [ "$1" == "--off" ]; then
    pkill -SIGINT -f "python3 script.py --option a"
    pkill -SIGINT -f "python3 script.py --option b"
fi
1 Like

It doesn’t seem to be working, to be clear, this is the actual script now instead of a simplified example:

#!/bin/bash

SCRIPT="$HOME/Scripts/lhctrl.py"

ID1="6202F1BF"
MAC1="74:F6:1C:04:F3:61"

ID2="6D1478E2"
MAC2="74:F6:1C:04:F2:58"


if [ "$1" == "--on" ]; then
    python3 $SCRIPT -b $ID1 --lh_b_mac $MAC1 &
    python3 $SCRIPT -b $ID2 --lh_b_mac $MAC2 &
elif [ "$1" == "--off" ]; then
    pkill -SIGTERM -f "python3 $SCRIPT -b $ID1 --lh_b_mac $MAC1"
    pkill -SIGTERM -f "python3 $SCRIPT -b $ID2 --lh_b_mac $MAC2"
fi

I had to use SIGTERM instead of SIGINT, cuz nothing happened with SIGINT. But it doesn’t quite work.

One of them closes properly, the other one doesn’t, and to close the other one i have to close the terminal which is the behavior i’m trying to get past.

This behavior isn’t making any sense to me.

EDIT: I get an error, on the terminal that ran the script when one of them fails to close, a python error. It only happens sometimes.

EDIT2: Using SIGKILL instead got rid of the error problem. Gonna mark your solution as the answer, thanks for the help!

1 Like

SIGKILL can be rather brutal. If these are your own Python scripts, I’d tend to implement a signal handler, so your Python code could react to it and gracefully shut down. :wink:

Python docs for signal
Example on StackOverflow (look for the accepted answer)

1 Like

It’s not actually my own, but it’s also kinda unnecessary in this case because what the code does is send a signal over bluetooth to the target devices every 20 seconds, and the point of stopping the script is to stop that signal from being sent (which lets the devices go to sleep).

But thanks for the input, I’ll keep it in mind if I write any python scripts of my own :slight_smile:

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.