Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Badly defined python code?
#1
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()
Reply
#2
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.
Reply
#3
(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.
buran write May-26-2023, 05:20 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable is not defined error when trying to use my custom function code fnafgamer239 4 601 Nov-23-2023, 02:53 PM
Last Post: rob101
  NameError: name 'u1' is not defined (on parser code Python) Melcu54 1 2,901 Jul-26-2021, 04:36 PM
Last Post: snippsat
  code not working, NameError: name 's' is not defined ridgerunnersjw 4 3,834 Oct-05-2020, 07:03 PM
Last Post: buran
  python library not defined in user defined function johnEmScott 2 3,885 May-30-2020, 04:14 AM
Last Post: DT2000
  Getting the error like function not defined .. suggest correct code raghava 1 2,060 Feb-04-2020, 11:20 PM
Last Post: micseydel
  NameError: name 'display' is not defined when running code on power bi beginner1 2 19,212 Jul-24-2019, 11:03 AM
Last Post: beginner1

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020