solo2500
Posts: 123
Joined: Sat Jul 09, 2016 12:38 am

syntax error on except KeyboardInterrupt:

Sun Feb 05, 2017 8:41 pm

I'm getting a syntax error on the except KeyboardInterrupt: at the end of this program... Any ideas?

Code: Select all

#!/usr/bin/python
# SoloJW
#
# This script controls a fan based on CPU temperature.
#
# It expects a fan that's externally powered, and uses GPIO(BCM) pin 26 for control.

import RPi.GPIO as GPIO
import time
import os

# Return CPU temperature as float
def getCPUtemp():
        cTemp = os.popen('vcgencmd measure_temp').readline()
        return float(cTemp.replace("temp=","").replace("'C\n",""))

GPIO.setmode(GPIO.BCM)
GPIO.setup(26,GPIO.OUT)
#GPIO.setwarnings(False)
GPIO.output(26, GPIO.LOW)
time.sleep(2)


while True:

        CPU_temp = getCPUtemp()

        print'CPU TEMP=' , CPU_temp

        if CPU_temp > 51.5:
                GPIO.output(26, GPIO.HIGH)
                print'FAN ON... CPU TEMP=' , CPU_temp

        elif CPU_temp < 50.0:
                GPIO.output(26, GPIO.LOW)
                print'FAN OFF... CPU TEMP=' , CPU_temp
        time.sleep(5)

except KeyboardInterrupt:
GPIO.cleanup()

   
Thanks for any help!
I'm a total novice, non-programer (...basically a hack.)

pcmanbob
Posts: 9467
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: syntax error on except KeyboardInterrupt:

Sun Feb 05, 2017 8:58 pm

Hi.

you need a try: statement.

like this

Code: Select all

try:
	while True:

			CPU_temp = getCPUtemp()

			print'CPU TEMP=' , CPU_temp

			if CPU_temp > 51.5:
					GPIO.output(26, GPIO.HIGH)
					print'FAN ON... CPU TEMP=' , CPU_temp

			elif CPU_temp < 50.0:
					GPIO.output(26, GPIO.LOW)
					print'FAN OFF... CPU TEMP=' , CPU_temp
			time.sleep(5)


except KeyboardInterrupt:
	GPIO.cleanup()
then it works ok.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

User avatar
rpdom
Posts: 17174
Joined: Sun May 06, 2012 5:17 am
Location: Chelmsford, Essex, UK

Re: syntax error on except KeyboardInterrupt:

Sun Feb 05, 2017 9:03 pm

An "except" needs a "try" at the start of the code block.

solo2500
Posts: 123
Joined: Sat Jul 09, 2016 12:38 am

Re: syntax error on except KeyboardInterrupt:

Sun Feb 05, 2017 11:26 pm

THANKS SO MUCH!!!
I'm a total novice, non-programer (...basically a hack.)

Return to “Beginners”