Python Forum
IndentationError: unexpected indent (Python) - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: IndentationError: unexpected indent (Python) (/thread-4362.html)



IndentationError: unexpected indent (Python) - segs - Aug-11-2017

Hi All,

I have this script that gives me a bunch of errors Please help. Am new to python

>>>
...     def create_zendesk_ticket(self,event_id,event_status):
  File "<stdin>", line 2
    def create_zendesk_ticket(self,event_id,event_status):
    ^
IndentationError: unexpected indent
>>>             collaborators = self.zbx_evt_recipients(event_id)
  File "<stdin>", line 1
    collaborators = self.zbx_evt_recipients(event_id)
    ^
IndentationError: unexpected indent
>>>             subject = self.ydata['trigger']['name']
  File "<stdin>", line 1
    subject = self.ydata['trigger']['name']
    ^
IndentationError: unexpected indent
>>>             #description = '%s\n\nZabbix severity: %s' % (self.ydata['desc'],self.ydata['trigger']['severity'])
...             description = self.ydata['desc'].replace('"','')
  File "<stdin>", line 2
    description = self.ydata['desc'].replace('"','')
    ^
IndentationError: unexpected indent
>>>             priority = 'high' if self.ydata['trigger']['severity'] == 'High' else 'normal'
  File "<stdin>", line 1
    priority = 'high' if self.ydata['trigger']['severity'] == 'High' else 'normal'
    ^
IndentationError: unexpected indent
>>>             tkt_data = { 'ticket': {
  File "<stdin>", line 1
    tkt_data = { 'ticket': {
    ^
IndentationError: unexpected indent
>>>                     'subject': subject,
  File "<stdin>", line 1
    'subject': subject,
    ^
IndentationError: unexpected indent
>>>                     'description': description,
  File "<stdin>", line 1
    'description': description,
    ^
IndentationError: unexpected indent
>>>                     'collaborators': collaborators,
  File "<stdin>", line 1
    'collaborators': collaborators,
    ^
IndentationError: unexpected indent
>>>                     'set_tags': ['test'],
  File "<stdin>", line 1
    'set_tags': ['test'],
    ^
IndentationError: unexpected indent
>>>                     'external_id': event_id,
  File "<stdin>", line 1
    'external_id': event_id,
    ^
IndentationError: unexpected indent
>>>                     'priority': priority,
  File "<stdin>", line 1
    'priority': priority,
    ^
IndentationError: unexpected indent
>>>                     'requester_id': self.zd_enduser['id'],
  File "<stdin>", line 1
    'requester_id': self.zd_enduser['id'],
    ^
IndentationError: unexpected indent
>>>                     'submitter_id': self.zd_enduser['id'],
  File "<stdin>", line 1
    'submitter_id': self.zd_enduser['id'],
    ^
IndentationError: unexpected indent
>>>                     'organization_id': self.zd_enduser['organization_id'],
  File "<stdin>", line 1
    'organization_id': self.zd_enduser['organization_id'],
    ^
IndentationError: unexpected indent
>>>             }}
  File "<stdin>", line 1
    }}
    ^
IndentationError: unexpected indent
>>>             ### Auto-close if status is "OK" and severity is "information"
...             if event_status == 'OK' and self.ydata['trigger']['severity'] == 'Information':
  File "<stdin>", line 2
    if event_status == 'OK' and self.ydata['trigger']['severity'] == 'Information':
    ^
IndentationError: unexpected indent
>>>                     tkt_data['ticket']['status'] = 'solved'
  File "<stdin>", line 1
    tkt_data['ticket']['status'] = 'solved'
    ^
IndentationError: unexpected indent
>>>                     tkt_data['ticket']['assignee_id'] = self.zd_user['id']
  File "<stdin>", line 1
    tkt_data['ticket']['assignee_id'] = self.zd_user['id']
    ^
IndentationError: unexpected indent
>>>
>>>             ### TODO: ADD TKT_ID as acknowledge comment
...             tkt_url = self.zd.create_ticket(data=tkt_data)
  File "<stdin>", line 2
    tkt_url = self.zd.create_ticket(data=tkt_data)
    ^
IndentationError: unexpected indent
>>>             tkt_id = get_id_from_url(tkt_url)
  File "<stdin>", line 1
    tkt_id = get_id_from_url(tkt_url)
    ^
IndentationError: unexpected indent
>>>             #tkt = self.zd.show_ticket(ticket_id=tkt_id)
...             #log.debug('Created ticket with ID %s'%tkt_id)
...             #log.debug(json.dumps(tkt,sort_keys=True,indent=2))
...             log.info('Created Zendesk ticket ID %s from Zabbix eventid %s' % (tkt_id,event_id))
  File "<stdin>", line 4
    log.info('Created Zendesk ticket ID %s from Zabbix eventid %s' % (tkt_id,event_id))
    ^
IndentationError: unexpected indent
>>>             #return tkt_id
...
>>>
>>>     def update_zendesk_ticket(self,event_id,event_status):
  File "<stdin>", line 1
    def update_zendesk_ticket(self,event_id,event_status):
    ^
IndentationError: unexpected indent
>>>             if event_status == 'OK':
  File "<stdin>", line 1
    if event_status == 'OK':
    ^
IndentationError: unexpected indent
>>>                     tkt = self.zd.list_all_tickets(external_id=event_id)
  File "<stdin>", line 1
    tkt = self.zd.list_all_tickets(external_id=event_id)
    ^
IndentationError: unexpected indent
>>>                     log.debug(tkt) # json.dumps(tkt,sort_keys=True,indent=2)
  File "<stdin>", line 1
    log.debug(tkt) # json.dumps(tkt,sort_keys=True,indent=2)
    ^
IndentationError: unexpected indent
>>>                     if tkt['count']==1:
  File "<stdin>", line 1
    if tkt['count']==1:
    ^
IndentationError: unexpected indent
>>>                             tkt_id = tkt['tickets'][0]['id']
  File "<stdin>", line 1
    tkt_id = tkt['tickets'][0]['id']
    ^
IndentationError: unexpected indent
>>>                             desc = self.ydata['desc'].replace('"','')
  File "<stdin>", line 1
    desc = self.ydata['desc'].replace('"','')
    ^
IndentationError: unexpected indent
>>>                             #log.info('Update ticket %s' % tkt_id)
...                             if self.ydata['trigger']['severity'] == 'High':
  File "<stdin>", line 2
    if self.ydata['trigger']['severity'] == 'High':
    ^
IndentationError: unexpected indent
>>>                                     tkt_data = {'ticket':{
  File "<stdin>", line 1
    tkt_data = {'ticket':{
    ^
IndentationError: unexpected indent
>>>                                             'comment':{'public':True, 'body': desc}
  File "<stdin>", line 1
    'comment':{'public':True, 'body': desc}
    ^
IndentationError: unexpected indent
>>>                                     }}
  File "<stdin>", line 1
    }}
    ^
IndentationError: unexpected indent
>>>                                     log.info('Updating ticket %s from Zabbix event %s' % (tkt_id,event_id))
  File "<stdin>", line 1
    log.info('Updating ticket %s from Zabbix event %s' % (tkt_id,event_id))
    ^
IndentationError: unexpected indent
>>>                             else:
  File "<stdin>", line 1
    else:
    ^
IndentationError: unexpected indent
>>>                                     tkt_data = {'ticket':{
  File "<stdin>", line 1
    tkt_data = {'ticket':{
    ^
IndentationError: unexpected indent
>>>                                             'status': 'solved',
  File "<stdin>", line 1
    'status': 'solved',
    ^
IndentationError: unexpected indent
>>>                                             'assignee_id': self.zd_user['id'],
  File "<stdin>", line 1
    'assignee_id': self.zd_user['id'],
    ^
IndentationError: unexpected indent
>>>                                             'comment':{
  File "<stdin>", line 1
    'comment':{
    ^
IndentationError: unexpected indent
>>>                                                     'public':True,
  File "<stdin>", line 1
    'public':True,
    ^
IndentationError: unexpected indent
>>>                                                     'author_id': self.zd_enduser['id'],
  File "<stdin>", line 1
    'author_id': self.zd_enduser['id'],
    ^
IndentationError: unexpected indent
>>>                                                     'body': '%s\n(Auto-closed by Zabbix)'%desc
  File "<stdin>", line 1
    'body': '%s\n(Auto-closed by Zabbix)'%desc
    ^
IndentationError: unexpected indent
>>>                                             }
  File "<stdin>", line 1
    }
    ^
IndentationError: unexpected indent
>>>                                     }}
  File "<stdin>", line 1
    }}
    ^
IndentationError: unexpected indent
>>>                                     log.info('Closing Zendesk ticket %s, event id: %s' % (tkt_id,event_id))
  File "<stdin>", line 1
    log.info('Closing Zendesk ticket %s, event id: %s' % (tkt_id,event_id))
    ^
IndentationError: unexpected indent
>>>
>>>                             tkt_up = self.zd.update_ticket(ticket_id=tkt_id,data=tkt_data)
  File "<stdin>", line 1
    tkt_up = self.zd.update_ticket(ticket_id=tkt_id,data=tkt_data)
    ^
IndentationError: unexpected indent
>>>                             #log.debug(json.dumps(tkt_up,sort_keys=True,indent=2))
...                             return True
  File "<stdin>", line 2
    return True
    ^
IndentationError: unexpected indent
>>>             return False
  File "<stdin>", line 1
    return False
    ^
IndentationError: unexpected indent
>>>
>>>
...     def mysql_s
  File "<stdin>", line 2
    def mysql_s
    ^
IndentationError: unexpected indent
>>>             try:
  File "<stdin>", line 1
    try:
    ^
IndentationError: unexpected indent
>>>                     # Get MySQL connection parameters from zabbix conf file
...                     with open(self.zabbix_conf) as f:
  File "<stdin>", line 2
    with open(self.zabbix_conf) as f:
    ^
IndentationError: unexpected indent
>>>                             my = dic
  File "<stdin>", line 1
    my = dic
    ^
IndentationError: unexpected indent
>>>                                     f.read().split('\n') if ln.
  File "<stdin>", line 1
    f.read().split('\n') if ln.
    ^
IndentationError: unexpected indent
>>>                     self.db = MySQLdb.connect(my['host'], my['user'], my['password'], my['name'])
  File "<stdin>", line 1
    self.db = MySQLdb.connect(my['host'], my['user'], my['password'], my['name'])
    ^
IndentationError: unexpected indent
>>>                     self.mycsr = self.db.cursor()
  File "<stdin>", line 1
    self.mycsr = self.db.cursor()
    ^
IndentationError: unexpected indent
>>>             except IOError as e:
  File "<stdin>", line 1
    except IOError as e:
    ^
IndentationError: unexpected indent
>>>                     log.error(e)
  File "<stdin>", line 1
    log.error(e)
    ^
IndentationError: unexpected indent
>>>                     return False
  File "<stdin>", line 1
    return False
    ^
IndentationError: unexpected indent
>>>             except KeyError as e:
  File "<stdin>", line 1
    except KeyError as e:
    ^
IndentationError: unexpected indent
>>>                     log.error('Could not find %s'%e)
  File "<stdin>", line 1
    log.error('Could not find %s'%e)
    ^
IndentationError: unexpected indent
>>>                     return False
  File "<stdin>", line 1
    return False
    ^
IndentationError: unexpected indent
>>>             else:
  File "<stdin>", line 1
    else:
    ^
IndentationError: unexpected indent
>>>                     return True
  File "<stdin>", line 1
    return True
    ^
IndentationError: unexpected indent
>>>
>>>
>>>     def get_zendesk_user(self,email):
  File "<stdin>", line 1
    def get_zendesk_user(self,email):
    ^
IndentationError: unexpected indent
>>>             cache_file = '/tmp/zendesk_user_%s' % email
  File "<stdin>", line 1
    cache_file = '/tmp/zendesk_user_%s' % email
    ^
IndentationError: unexpected indent
>>>             try:
  File "<stdin>", line 1
    try:
    ^
IndentationError: unexpected indent
>>>                     if time()-path.getmtime(cache_file) > 86400:
  File "<stdin>", line 1
    if time()-path.getmtime(cache_file) > 86400:
    ^
IndentationError: unexpected indent
>>>                             remove(cache_file)
  File "<stdin>", line 1
    remove(cache_file)
    ^
IndentationError: unexpected indent
>>>                             log.debug('Cache file deleted')
  File "<stdin>", line 1
    log.debug('Cache file deleted')
    ^
IndentationError: unexpected indent
>>>                     with open(cache_file, 'r') as f:
  File "<stdin>", line 1
    with open(cache_file, 'r') as f:
    ^
IndentationError: unexpected indent
>>>                             data = yaml.load(f.read())
  File "<stdin>", line 1
    data = yaml.load(f.read())
    ^
IndentationError: unexpected indent
>>>             except:
  File "<stdin>", line 1
    except:
    ^
IndentationError: unexpected indent
>>>                     data = self.zd.search_user(query='email:%s'%email)['users'][0]
  File "<stdin>", line 1
    data = self.zd.search_user(query='email:%s'%email)['users'][0]
    ^
IndentationError: unexpected indent
>>>                     with open(cache_file, 'w') as f:
  File "<stdin>", line 1
    with open(cache_file, 'w') as f:
    ^
IndentationError: unexpected indent
>>>                             f.write(yaml.dump(data) )
  File "<stdin>", line 1
    f.write(yaml.dump(data) )
    ^
IndentationError: unexpected indent
>>>
...             return data
  File "<stdin>", line 2
    return data
    ^
IndentationError: unexpected indent
>>>
...
>>>     def zbx_evt_recipients(self,event_id):
  File "<stdin>", line 1
    def zbx_evt_recipients(self,event_id):
    ^
IndentationError: unexpected indent
>>>             rows = ['[email protected]']
  File "<stdin>", line 1
    rows = ['[email protected]']
    ^
IndentationError: unexpected indent
>>>             try:
  File "<stdin>", line 1
    try:
    ^
IndentationError: unexpected indent
>>>                     sql = """SELECT m.sendto mail
  File "<stdin>", line 1
    sql = """SELECT m.sendto mail
    ^
IndentationError: unexpected indent
>>> FROM events e,functions f,items i, hosts_groups hg, groups g, users_groups uxg, usrgrp ug, media m
  File "<stdin>", line 1
    FROM events e,functions f,items i, hosts_groups hg, groups g, users_groups uxg, usrgrp ug, media m
              ^
SyntaxError: invalid syntax
>>> WHERE e.eventid=%s
  File "<stdin>", line 1
    WHERE e.eventid=%s
          ^
SyntaxError: invalid syntax
>>> AND e.object=0
  File "<stdin>", line 1
    AND e.object=0
        ^
SyntaxError: invalid syntax
>>> AND e.source=0
  File "<stdin>", line 1
    AND e.source=0
        ^
SyntaxError: invalid syntax
>>> AND e.objectid=f.triggerid
  File "<stdin>", line 1
    AND e.objectid=f.triggerid
        ^
SyntaxError: invalid syntax
>>> AND f.itemid=i.itemid
  File "<stdin>", line 1
    AND f.itemid=i.itemid
        ^
SyntaxError: invalid syntax
>>> AND hg.hostid=i.hostid
  File "<stdin>", line 1
    AND hg.hostid=i.hostid
         ^
SyntaxError: invalid syntax
>>> AND ug.usrgrpid=uxg.usrgrpid
  File "<stdin>", line 1
    AND ug.usrgrpid=uxg.usrgrpid
         ^
SyntaxError: invalid syntax
>>> AND m.userid=uxg.userid
  File "<stdin>", line 1
    AND m.userid=uxg.userid
        ^
SyntaxError: invalid syntax
>>> AND LOWER(g.name)=LOWER(ug.name)
  File "<stdin>", line 1
    AND LOWER(g.name)=LOWER(ug.name)
            ^
SyntaxError: invalid syntax
>>> AND hg.groupid=g.groupid;"""
  File "<stdin>", line 1
    AND hg.groupid=g.groupid;"""
         ^
SyntaxError: invalid syntax
>>>                     self.mycsr.execute(sql % event_id)
  File "<stdin>", line 1
    self.mycsr.execute(sql % event_id)
    ^
IndentationError: unexpected indent
>>>                     rows.extend([ r[0] for r in self.mycsr.fetchall() ])
  File "<stdin>", line 1
    rows.extend([ r[0] for r in self.mycsr.fetchall() ])
    ^
IndentationError: unexpected indent
>>>                     return rows
  File "<stdin>", line 1
    return rows
    ^
IndentationError: unexpected indent
>>>             except:
  File "<stdin>", line 1
    except:
    ^
IndentationError: unexpected indent
>>>                     return rows
  File "<stdin>", line 1
    return rows
    ^
IndentationError: unexpected indent
>>>
>>> ### END OF CLASS ###
...
>>> if __name__ == '__main__':
...     try:
...             exit(z2z())
...     except Exception as e:
...             log.error(e)



RE: IndentationError: unexpected indent (Python) - radioactive9 - Aug-11-2017

Hello

Indentation error is because you have mixed space with tab.
Or
You have given logical wrong indents
Also you did not post the actual code for us to see the indents that you have used. Looking at the code you seem to be creating some class is all any one can say

def create_zendesk_ticket(self,event_id,event_status):
for e.g it should ideally be at the left most corner without any space or tab before the word def


RE: IndentationError: unexpected indent (Python) - ichabod801 - Aug-11-2017

(Aug-11-2017, 01:43 AM)radioactive9 Wrote: def create_zendesk_ticket(self,event_id,event_status):
for e.g it should ideally be at the left most corner without any space or tab before the word def

No, it's clearly part of a class definition (first parameter is self). So it should be indented at least one level, to be part of the class code block.

It looks like you (OP) are entering the code at the command line. Did you enter blank lines? That could confuse the interpreter into thinking your class definition is finished.


RE: IndentationError: unexpected indent (Python) - segs - Aug-11-2017

Apologies, Please find the complete code/script, When i test online there seem to be lot of those error coming up.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

 
import json
import logging as log
import MySQLdb
import yaml
from sys import argv
from time import time
from os import path, remove
from zendesk import Zendesk, get_id_from_url
from inspect import currentframe
import collections

log.basicConfig(level=log.DEBUG, filename='/var/log/zabbix/zendesk.log', 
	format='%(asctime)s %(levelname)s %(message)s')

def lino(): return currentframe().f_back.f_lineno

class z2z:
	def __init__(self):
		if not argv[1].startswith('support@'):
			log.debug('wrong argument 1: %s' % argv[1] )
			exit(2)
		self.zabbix_conf = '/etc/zabbix/zabbix_server.conf'
		try:
			# Input data mangling
			self.ydata = yaml.load(argv[3])
			log.debug(argv[3])
			event_id = argv[2].split(':')[0]
			event_status = argv[2].split(':')[1].strip()
			log.debug('event_id:%s, event_status:%s' % (event_id,event_status))
			# Establish MySQL connection
			self.mysql_setup()
			# Zendesk setup
			self.mycsr.execute("SELECT lower(macro),value FROM globalmacro WHERE macro like '%ZENDESK%';")
			self.zdp = dict([ (macro[10:-1], value) for (macro,value) in self.mycsr.fetchall() ])
			self.zd = Zendesk(self.zdp['url'], self.zdp['email'], self.zdp['token'], api_version=2,
				use_api_token=True, client_args={ "disable_ssl_certificate_validation": True })
			self.zd_user = self.get_zendesk_user(self.zdp['email'])
			self.zd_enduser = self.get_zendesk_user(self.zdp['enduser'])
			
			# If the status is 'OK' and we can find the ticket 
			# matching our external_id we close the ticket
			if not self.update_zendesk_ticket(event_id,event_status):
				self.create_zendesk_ticket(event_id,event_status)
			self.db.close()
			exit(0)
		except Exception as e:
			log.error('Failed with: [%s]. Ciao!' % e)
			exit(1)

	
	def create_zendesk_ticket(self,event_id,event_status):
		collaborators = self.zbx_evt_recipients(event_id)	
		subject = self.ydata['trigger']['name']
		#description = '%s\n\nZabbix severity: %s' % (self.ydata['desc'],self.ydata['trigger']['severity'])
		description = self.ydata['desc'].replace('"','')
		priority = 'high' if self.ydata['trigger']['severity'] == 'High' else 'normal'
		tkt_data = { 'ticket': {
			'subject': subject,
			'description': description,
			'collaborators': collaborators,
			'set_tags': ['test'],
			'external_id': event_id,
			'priority': priority,
			'requester_id': self.zd_enduser['id'],
			'submitter_id': self.zd_enduser['id'],
			'organization_id': self.zd_enduser['organization_id'],
		}}
		### Auto-close if status is "OK" and severity is "information"
		if event_status == 'OK' and self.ydata['trigger']['severity'] == 'Information':
			tkt_data['ticket']['status'] = 'solved'
			tkt_data['ticket']['assignee_id'] = self.zd_user['id']

		### TODO: ADD TKT_ID as acknowledge comment
		tkt_url = self.zd.create_ticket(data=tkt_data)
		tkt_id = get_id_from_url(tkt_url)
		#tkt = self.zd.show_ticket(ticket_id=tkt_id)
		#log.debug('Created ticket with ID %s'%tkt_id)
		#log.debug(json.dumps(tkt,sort_keys=True,indent=2))
		log.info('Created Zendesk ticket ID %s from Zabbix eventid %s' % (tkt_id,event_id))
		#return tkt_id


	def update_zendesk_ticket(self,event_id,event_status):
		if event_status == 'OK':
			tkt = self.zd.list_all_tickets(external_id=event_id)
			log.debug(tkt) # json.dumps(tkt,sort_keys=True,indent=2)
			if tkt['count']==1:
				tkt_id = tkt['tickets'][0]['id']
				desc = self.ydata['desc'].replace('"','')
				#log.info('Update ticket %s' % tkt_id)
				if self.ydata['trigger']['severity'] == 'High':
					tkt_data = {'ticket':{
						'comment':{'public':True, 'body': desc}
					}}
					log.info('Updating ticket %s from Zabbix event %s' % (tkt_id,event_id))
				else:
					tkt_data = {'ticket':{
						'status': 'solved',
						'assignee_id': self.zd_user['id'],
						'comment':{
							'public':True, 
							'author_id': self.zd_enduser['id'],
							'body': '%s\n(Auto-closed by Zabbix)'%desc
						}
					}}
					log.info('Closing Zendesk ticket %s, event id: %s' % (tkt_id,event_id))

				tkt_up = self.zd.update_ticket(ticket_id=tkt_id,data=tkt_data)
				#log.debug(json.dumps(tkt_up,sort_keys=True,indent=2))
				return True
		return False

	
	def mysql_setup(self):
		try:
			# Get MySQL connection parameters from zabbix conf file
			with open(self.zabbix_conf) as f:
				my = dict( ln.lower()[2:].split('=') for ln in
					f.read().split('\n') if ln.startswith('DB') )
			self.db = MySQLdb.connect(my['host'], my['user'], my['password'], my['name'])
			self.mycsr = self.db.cursor()
		except IOError as e:
			log.error(e)
			return False
		except KeyError as e: 
			log.error('Could not find %s'%e)
			return False
		else:
			return True


	def get_zendesk_user(self,email):
		cache_file = '/tmp/zendesk_user_%s' % email
		try:
			if time()-path.getmtime(cache_file) > 86400:
				remove(cache_file)
				log.debug('Cache file deleted')
			with open(cache_file, 'r') as f: 
				data = yaml.load(f.read())
		except:
			data = self.zd.search_user(query='email:%s'%email)['users'][0]
			with open(cache_file, 'w') as f: 
				f.write(yaml.dump(data) )
		
		return data
			

	def zbx_evt_recipients(self,event_id):
		rows = ['[email protected]']
		try:
			sql = """SELECT m.sendto mail
FROM events e,functions f,items i, hosts_groups hg, groups g, users_groups uxg, usrgrp ug, media m
WHERE e.eventid=%s 
AND e.object=0 
AND e.source=0 
AND e.objectid=f.triggerid 
AND f.itemid=i.itemid 
AND hg.hostid=i.hostid 
AND ug.usrgrpid=uxg.usrgrpid
AND m.userid=uxg.userid 
AND LOWER(g.name)=LOWER(ug.name) 
AND hg.groupid=g.groupid;"""
			self.mycsr.execute(sql % event_id)
			rows.extend([ r[0] for r in self.mycsr.fetchall() ])
			return rows
		except:
			return rows

### END OF CLASS ###

if __name__ == '__main__':
	try:
		exit(z2z())
	except Exception as e:
		log.error(e)



RE: IndentationError: unexpected indent (Python) - ichabod801 - Aug-11-2017

I cannot fully run that script, because I don't have all of those packages installed. However, I'm getting an ImportError when I run it. IndentationErrors should trigger before ImportErrors. In fact, I intentionally added an IndentationError, and it triggered first. So I think the problem is not in your code, but in the online tool that you are using to test it.

Is there some reason you can't test it on a local machine? If there is, I would suggest removing blank lines from your code and seeing if that works. What online tool are you using?


RE: IndentationError: unexpected indent (Python) - segs - Aug-11-2017

(Aug-11-2017, 12:28 PM)ichabod801 Wrote: I cannot fully run that script, because I don't have all of those packages installed. However, I'm getting an ImportError when I run it. IndentationErrors should trigger before ImportErrors. In fact, I intentionally added an IndentationError, and it triggered first. So I think the problem is not in your code, but in the online tool that you are using to test it.

Is there some reason you can't test it on a local machine? If there is, I would suggest removing blank lines from your code and seeing if that works. What online tool are you using?

Hi ichabod801, Thank you for taking the time to look at this for me. I have ran this code on a python Window and it still comes with Indent errors. I am currently running this script from this online tool http://pep8online.com/ which seems to come with the errors and the lines.


RE: IndentationError: unexpected indent (Python) - ichabod801 - Aug-11-2017

That online tool is not for running code. It is for checking code against a particular style guide (PEP8). It will catch syntax errors, but it does not distinguish between style errors and syntax errors. When I copy and paste your code in there, I don't get an unexpected indent error. I do get a bunch of style "errors", but that shouldn't prevent your code from running in a proper Python interpreter.

It really looks to me that you are pasting this code into the Python interpreter. That's not the way to get that code to run. You either want to call the python from the command line with program file as a parameter, import the code into the parameter, or send the code to Python with an IDE.

There are tutorials on setting up Python and running programs in the tutorials section. I would look into those to make sure you are running the program correctly.


RE: IndentationError: unexpected indent (Python) - snippsat - Aug-11-2017

(Aug-11-2017, 02:13 PM)segs Wrote: I am currently running this script from this online tool http://pep8online.com/ which seems to come with the errors and the lines.
I was wondering how you did that mess in first post.
pep8online is not for running code,it's getting advice for better code quality. 

You can not run that script online,
it has a lot of dependencies and has MySQL connection to locals files.
# Get MySQL connection parameters from zabbix conf file
with open(self.zabbix_conf) as f:
    my = dict( ln.lower()[2:].split('=') for ln in
    f.read().split('\n') if ln.startswith('DB') )
    self.db = MySQLdb.connect(my['host'], my['user'], my['password'], my['name'])
    self.mycsr = self.db.cursor()
There is repl.it that can run Python code online.
Will of course not work with tihs script as mention


RE: IndentationError: unexpected indent (Python) - segs - Aug-11-2017

(Aug-11-2017, 02:32 PM)snippsat Wrote:
(Aug-11-2017, 02:13 PM)segs Wrote: I am currently running this script from this online tool http://pep8online.com/ which seems to come with the errors and the lines.
I was wondering how you did that mess in first post.
pep8online is not for running code,it's getting advice for better code quality. 

You can not run that script online,
it has a lot of dependencies and has MySQL connection to locals files.
# Get MySQL connection parameters from zabbix conf file
with open(self.zabbix_conf) as f:
    my = dict( ln.lower()[2:].split('=') for ln in
    f.read().split('\n') if ln.startswith('DB') )
    self.db = MySQLdb.connect(my['host'], my['user'], my['password'], my['name'])
    self.mycsr = self.db.cursor()
There is repl.it that can run Python code online.
Will of course not work with tihs script as mention

Ah Thank you, when i run it there i get ^
SyntaxError: invalid syntax error