jpsaenz
Posts: 1
Joined: Fri Dec 29, 2017 4:16 pm

except KeyboardInterrupt: invalid Syntax

Fri Dec 29, 2017 4:25 pm

im working on python 3, I keep getting invalid syntax error, i have looked for the error in other forums but i could not solve my problem, thank you!

Code: Select all

import RPi.GPIO as GPIO
import dht11
import time
import datetime
import csv
import sys

csvfile="temp.csv"
# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

# read data using pin 14
instance = dht11.DHT11(pin=17)
als = True
while als:
    result = instance.read()
    if result.is_valid():
        #print("Last valid input: " + str(datetime.datetime.now()))
        #time = datetime.datetime.now()
        print("Temperature: %d C" % result.temperature)
        temperature=result.temperature
        print("Humidity: %d %%" % result.humidity)
        humidity = result.humidity
    data=[temperature,humidity]

    
    with open(csvfile, "a")as output:
        writer = csv.writer(output, delimiter=",", lineterminator = '\n')
        writer.writerow(data)
    time.sleep(1)
    
    except KeyboardInterrupt:
        als=False

    

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

Re: except KeyboardInterrupt: invalid Syntax

Fri Dec 29, 2017 7:12 pm

To use except keyboardinterrupt : you need to have a try: statement first in your code.

Add it just before your while statement.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

mustafadeniz.kocan
Posts: 6
Joined: Fri Sep 07, 2018 7:46 am

Re: except KeyboardInterrupt: invalid Syntax

Tue Sep 11, 2018 1:52 pm

It can be too late but maybe someone use the correct code as below :

Code: Select all

import RPi.GPIO as GPIO
import dht11
import time
import datetime
import csv
import sys

csvfile = "/home/pi/DHT11_Python/temp12.csv"
# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

# read data using pin 23
instance = dht11.DHT11(pin=23)

try:
    while True:
        result = instance.read()
        if result.is_valid():
            print("Last valid input: " + str(datetime.datetime.now()))
            time = datetime.datetime.now()
            print("Temperature: %d C" % result.temperature)
            temperature = result.temperature
            print("Humidity: %d %%" % result.humidity)
            humidity = result.humidity
            data = [temperature, humidity]

    with open(csvfile, "a")as output:
        writer = csv.writer(output, delimiter=",", lineterminator='\n')
        writer.writerow(data)

finally:
    GPIO.cleanup()

Return to “Troubleshooting”