I'm running a python script from boot on my Raspberry Pi B running Raspbian. I set the raspi-config
so it is console auto logon. And I have the script that I want to run from boot into /etc/profile
and I added to the very last line of that file sudo python /link/to/script.py
. The script runs absolutely perfect. However, when I come to terminate it, it does not always work.
I am pressing CTRL + C
and CTRL + Z
to try and exit but it doesn't always work. It just prints ^C
or ^Z
into the terminal.
The script I am running sits in a while True
loop as it is sending data from a sensor and I need it to be sending the data all of the time.
This is the script
import paho.mqtt.publish as publish
from gpiozero import DistanceSensor
import requests
import RPi.GPIO as GPIO
import signal
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(20,GPIO.OUT)
GPIO.setup(21,GPIO.OUT)
ultrasonic = DistanceSensor(echo=17, trigger=4, max_distance=4)
print (ultrasonic.distance)
def connection_check():
try:
requests.get("http://google.com", timeout=1)
return True
except:
GPIO.output(21, GPIO.LOW)
GPIO.output(20,GPIO.HIGH)
#print("CONNECTION LOST...")
#print("RETRYING...")
pass
return False
while True:
if connection_check() == True:
GPIO.output(21, GPIO.HIGH)
GPIO.output(20, GPIO.LOW)
#print (ultrasonic.distance)
distance = ultrasonic.distance
publish.single("test/message",distance, hostname="172.18.65.XXX")
Has anyone had an issue like this and how do I get around it, sometimes it can take upwards of 10 minutes to try and terminate the script.
2 Answers 2
CTRL + C
sends an SIGINT signal to the active program and the program you are trying to terminate is not the active program at the time.
In such cases I like to save the process id in a file and later kill the process with with that process id.
To do so, I create 2 files, a start.sh
and a stop.sh
. I start my script using start.sh
and stop it using the stop.sh
The start.sh
#!/bin/bash
echo "Starting my script..."
nohup python /link/to/script.py > /link/to/script.process.log 2>&1&
echo $! > /link/to/script.process.pid
echo "My script is now running."
The stop.sh
#!/bin/bash
echo "Stopping my script..."
kill -9 `cat /link/to/script.process.pid`
echo "My script is now stopped."
If this is the only Python script you have running try
sudo killall python
or in extreme cases
sudo killall -9 python
You would need to give details of your script to know why ctrl-c sometimes works.
when I come to terminate it, it does not always work
? Do you just typeCTRL+C
andCTRL+Z
into your terminal?