Python Forum

Full Version: Badly defined python code?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?

#!/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()
The previous "line" is the config = on line 11.

The closing parenthesis for the config expression doesn't matter. But the indentation of line 11 does.
Line 20 does not have the same indentation as line 11, so it is flagged.

You might want to work with an editor that will enforce consistent indentation. I think line 32 and 91 will also have problems.
(May-25-2023, 08:06 PM)Ken76 Wrote: [ -> ]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?

#!/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()

Try using the following code and see if this helps:

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

pin = 2
sensor = Adafruit_DHT.DHT22

def measure():
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)

while True:
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
temperature = round(temperature, 2)
humidity = round(humidity, 2)
if humidity is not None and 0.0 <= humidity <= 100.0 and temperature is not None and -100.0 < temperature < 150.0:
mySql_insert_query = "INSERT INTO weather(temp, hum, station) VALUES (%s, %s, %s)"
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 view_status():
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)

while True:
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
temperature = round(temperature, 2)
humidity = round(humidity, 2)
if humidity is not None and 0.0 <= humidity <= 100.0 and temperature is not None and -100.0 < temperature < 150.0:
mySql_insert_query = "UPDATE showinfo SET temp = %s, hum = %s WHERE id = %s"
record = (temperature, humidity, 1)
cursor.execute(mySql_insert_query, record)
connection.commit()
print("Record updated successfully in table showinfo", temperature, " ", humidity)
cursor.close()
time.sleep(300)
except mysql.connector.Error as error:
print("Failed to update record in table {}".format(error))
finally:
if connection.is_connected():
connection.close()
print("MySQL connection is closed")

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

Here are the changes made:

Fixed indentation inconsistencies.
Removed unnecessary import of MySQLdb module since mysql.connector is already imported.
Fixed the indentation of exception handling blocks.
Corrected the query syntax in mySql_insert_query statements.
Updated print statements for successful record insertion and update.
Renamed the viewstatus function to view_status to follow Python naming conventions.
Ensured proper handling of connection closing in the finally blocks.
Fixed minor typos and formatting issues.