如何处理IndentationError:意外的缩进

时间:2018-07-30 07:03:09

标签: python python-3.x indentation

我目前正在使用树莓派,并使用DHT11每秒读取一次温度和湿度值。我必须将这些值实时保存到数据库中。这是我的代码,每秒显示一次传感器数据。

#!/usr/bin/python

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

dht11_pin = 17
limit_sec = 15 #15 sec

# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

sleep_time = 1
instance = dht11.DHT11(pin=dht11_pin)
previous_temperature = 0
previous_humidity = 0
with open('test.csv', 'w', newline='') as csvfile:
    field_names = ['Date', 'Time', 'Status', 'Temperature', 'Humidity']
    writer = csv.DictWriter(csvfile, fieldnames=field_names)
    writer.writerow({'Date': 'Date', 'Time': 'Time','Status': 'Status', 'Temperature': 'Temperature', 'Humidity': 'Humidity'})

    try:
        print "DHT11 Module Test (CTRL+C to exit)"
        print "please wait..."
        time.sleep(2)
        now = datetime.datetime.now()
        print("Ready! "+ now.strftime("%d/%m/%Y") + " / " + now.strftime("%H:%M:%S"))
        result = instance.read()
        if result.is_valid():
            now = datetime.datetime.now()
            print("Initial valid input: " + now.strftime("%d/%m/%Y") + " / " + now.strftime("%H:%M:%S"))
            print("Temperature: %d C" % result.temperature)
            print("Humidity: %d %%" % result.humidity)
            print("*******************************************")

            previous_temperature = result.temperature
            previous_humidity = result.humidity
        else:
            print "Invalid result!"
            pass

        counter = 0
        cnt = 0

        while True:

            cnt += 1
            if cnt%limit_sec == 0 or cnt == 1:

                result = instance.read()
                if result.is_valid():

                    if previous_temperature != result.temperature or previous_humidity != result.humidity:

                        previous_temperature = result.temperature
                        previous_humidity = result.humidity

                        counter += 1
                        rightnow = datetime.datetime.now()

                        if result.humidity>=40:
                            status = 'Good condition.'
                            print(str(counter)+". Last valid input: " )
                            print("Date: " + rightnow.strftime("%d/%m/%Y"))
                            print("Time: " + rightnow.strftime("%H:%M:%S"))
                            print("Status: Your plant is on the good condition.")
                            print("Temperature: %d C" % result.temperature)
                            print("Humidity: %d %%" % result.humidity)
                            print("*******************************************")


                        else:
                            status = 'Bad condition'
                            print(str(counter)+". Last valid input: " )
                            print("Date: " + rightnow.strftime("%d/%m/%Y"))
                            print("Time: " + rightnow.strftime("%H:%M:%S"))
                            print("Status: Your plant is on the bad condition. Please open the water supply.")
                            print("Temperature: %d C" % result.temperature)
                            print("Humidity: %d %%" % result.humidity)
                            print("*******************************************")
                        writer.writerow({'Date': rightnow.strftime("%d/%m/%Y"), 'Time': rightnow.strftime("%H:%M:%S"), 'Status': status, 'Temperature':result.temperature, 'Humidity': result.humidity})   
                else:
                    print "Invalid result!"
                    pass

            time.sleep(sleep_time)

except KeyboardInterrupt:
        print " Quit"
        GPIO.cleanup()

运行脚本时,出现以下错误:

  

以open('test.csv','w',newline ='')作为csvfile:

     

^

     

IndentationError:意外缩进

1 个答案:

答案 0 :(得分:0)

您在try except中出现缩进错误,两者应使用相同的缩进

简而言之,它应该是:

imports.....
.
.
.
with open('test.csv', 'w', newline='') as csvfile:
    .
    .
    .
    try:
        .
        .
    except:
    .
    .

(已解决)完整代码:

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

dht11_pin = 17
limit_sec = 15 #15 sec

# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

sleep_time = 1
instance = dht11.DHT11(pin=dht11_pin)
previous_temperature = 0
previous_humidity = 0
with open('test.csv', 'w', newline='') as csvfile:
    field_names = ['Date', 'Time', 'Status', 'Temperature', 'Humidity']
    writer = csv.DictWriter(csvfile, fieldnames=field_names)
    writer.writerow({'Date': 'Date', 'Time': 'Time','Status': 'Status', 'Temperature': 'Temperature', 'Humidity': 'Humidity'})

    try:
        print "DHT11 Module Test (CTRL+C to exit)"
        print "please wait..."
        time.sleep(2)
        now = datetime.datetime.now()
        print("Ready! "+ now.strftime("%d/%m/%Y") + " / " + now.strftime("%H:%M:%S"))
        result = instance.read()
        if result.is_valid():
            now = datetime.datetime.now()
            print("Initial valid input: " + now.strftime("%d/%m/%Y") + " / " + now.strftime("%H:%M:%S"))
            print("Temperature: %d C" % result.temperature)
            print("Humidity: %d %%" % result.humidity)
            print("*******************************************")

            previous_temperature = result.temperature
            previous_humidity = result.humidity
        else:
            print "Invalid result!"
            pass

        counter = 0
        cnt = 0

        while True:

            cnt += 1
            if cnt%limit_sec == 0 or cnt == 1:

                result = instance.read()
                if result.is_valid():

                    if previous_temperature != result.temperature or previous_humidity != result.humidity:

                        previous_temperature = result.temperature
                        previous_humidity = result.humidity

                        counter += 1
                        rightnow = datetime.datetime.now()

                        if result.humidity>=40:
                            status = 'Good condition.'
                            print(str(counter)+". Last valid input: " )
                            print("Date: " + rightnow.strftime("%d/%m/%Y"))
                            print("Time: " + rightnow.strftime("%H:%M:%S"))
                            print("Status: Your plant is on the good condition.")
                            print("Temperature: %d C" % result.temperature)
                            print("Humidity: %d %%" % result.humidity)
                            print("*******************************************")


                        else:
                            status = 'Bad condition'
                            print(str(counter)+". Last valid input: " )
                            print("Date: " + rightnow.strftime("%d/%m/%Y"))
                            print("Time: " + rightnow.strftime("%H:%M:%S"))
                            print("Status: Your plant is on the bad condition. Please open the water supply.")
                            print("Temperature: %d C" % result.temperature)
                            print("Humidity: %d %%" % result.humidity)
                            print("*******************************************")
                        writer.writerow({'Date': rightnow.strftime("%d/%m/%Y"), 'Time': rightnow.strftime("%H:%M:%S"), 'Status': status, 'Temperature':result.temperature, 'Humidity': result.humidity})   
                else:
                    print "Invalid result!"
                    pass

            time.sleep(sleep_time)

    except KeyboardInterrupt:
            print " Quit"
            GPIO.cleanup()