Kenne76
Posts: 1
Joined: Thu May 25, 2023 8:26 pm

Badly defined python code?

Thu May 25, 2023 8:31 pm

I get following error message with my python code.
File "/home/ken/Programming/temp.py", line 20
try:
IndentationError: unexpected indent

I have defined my code apparently badly, but I can't figure out what the issue is.
Here is the code. Can someone help me?

Code: Select all

#!/usr/bin/python
import mysql.connector, sys, MySQLdb, Adafruit_DHT, datetime, time, multiprocessing
from mysql.connector import Error
from mysql.connector import errorcode

pin = 2
sensor = Adafruit_DHT.DHT22

def messaure():

    config = {
      'host':'**************',
      'user':'********',
      'password':'**********',
      'database':'**************',
      'client_flags': [mysql.connector.ClientFlag.SSL],
      'ssl_ca': '/home/ken/shared/Cert/DigiCertGlobalRootG2.crt.pem'
     }

     try: 
         connection = mysql.connector.connect(**config)
         if connection.is_connected():
            db_Info = connection.get_server_info()
            print("Connected to MySQL Server version ", db_Info)
            cursor = connection.cursor()
            cursor.execute("select database();")
            record = cursor.fetchone()
            print("You're connected to database: ", record)

          #except Error as e:
          #   print("Error while connecting to MySQL", e)
            while True:
               humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
               temperature=(round(temperature,2));
               humidity=(round(humidity,2));
               if humidity is not None and humidity >= 0.0 and humidity <= 100.0 and temperature is not None and temperature > -100.0 and temperature < 150.0:
                  mySql_insert_query = """INSERT INTO weather(temp, hum, station) VALUES ('%s','%s','%s')"""
                  cursor = connection.cursor()
                  record = (temperature, humidity, 1)
                  cursor.execute(mySql_insert_query, record)
                  connection.commit()
                  print("Record inserted successfully into table weather", temperature, " ", humidity)
                  cursor.close()
                  with open("/home/ken/shared/Measurement/values.txt", "r") as r:
                     value = r.read()   
                     delay = int(value.strip()) * 60  
                     print("The delay is: ", delay)
                     time.sleep(delay)
      except mysql.connector.Error as error:
                 print("Failed to insert record into table {}".format(error))
      finally:
         if (connection.is_connected()):
            connection.close()
            print("MySQL connection is closed")

def viewstatus():

     config = {
       'host':'*******',
       'user':'*****',
       'password':'**********',
       'database':'**********',
     }

     try:
         connection = mysql.connector.connect(**config)
         if connection.is_connected():
            db_Info = connection.get_server_info()
            print("Connected to MySQL Server version ", db_Info)
            cursor = connection.cursor()
            cursor.execute("select database();")
            record = cursor.fetchone()
            print("You're connected to database: ", record)

            #except Error as e:
            #   print("Error while connecting to MySQL", e)
            while True:
               humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
               temperature=(round(temperature,2));
               humidity=(round(humidity,2));
               if humidity is not None and humidity >= 0.0 and humidity <= 100.0 and temperature is not None and temperature > -100.0 and temperature < 150.0:
                  mySql_insert_query = """UPDATE showinfo set temp ='%s', hum='%s's where id ='1')"""
                  cursor = connection.cursor()
                  record = (temperature, humidity, 1)
                  cursor.execute(mySql_insert_query, record)
                  connection.commit()
                  print("Record inserted successfully into table weather", temperature, " ", humidity)
                  cursor.close()
                  print("The delay is: ", delay)
                  time.sleep(300)
       except mysql.connector.Error as error:
            print("Failed to insert record into table {}".format(error))

     finally:
        if (connection.is_connected()):
           connection.close()
           print("MySQL connection is closed")

if __name__ == '__main__':
    p1 = multiprocessing.Process(name='p1', target=messaure)
    p = multiprocessing.Process(name='p', target=viewstatus)
    p1.start()
    p.start()

ghp
Posts: 3251
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany

Re: Badly defined python code?

Thu May 25, 2023 9:39 pm

This is the problem: " ", should be this " ". Not clear ? Here a better explanation:
4_5.png
4_5.png (97.6 KiB) Viewed 159 times
The 'config = {' has four blank indentation, the 'try:' has 5 blank.

There are editor around which can "display whitespace". The screenshot is from notepad++.

ame
Posts: 7085
Joined: Sat Aug 18, 2012 1:21 am
Location: New Zealand

Re: Badly defined python code?

Thu May 25, 2023 10:03 pm

Kenne76 wrote:
Thu May 25, 2023 8:31 pm
I get following error message with my python code.
File "/home/ken/Programming/temp.py", line 20
try:
IndentationError: unexpected indent

I have defined my code apparently badly, but I can't figure out what the issue is.
The issue is that on line 20 there is an unexpected indent.

What it means is that the indentation does not match the block that the code is in. As ghp says, count the spaces and see where you went wrong.
Hmm. What can I put here?

Return to “Python”