0

Code

#!/usr/bin/python
import sys
import psycopg2
import psycopg2.extras

def init_pg94_from_sql_file(filename, connection):        
    file = open(filename, 'r')
    sql = s = " ".join(file.readlines())
    print "Start executing: " + filename + " at " + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")) + "\n" + sql 
    cursor = connection.cursor()
    cursor.execute(sql)    

    connection.commit()
    cursor.close()

but I get

  File "9.7.2015.py", line 14
    cursor.close()
    ^
IndentationError: unexpected indent

which is strange, since I do not seem to have any indentation problem.

How can you handle such an unexpected indentation challenge?

Léo Léopold Hertz 준영
  • 134,464
  • 179
  • 445
  • 697
  • 2
    Double-check your indentation! You may have a stray space or a stray tab causing issues! (I'd recommend you re-indent your code, using spaces alone.) – NightShadeQueen Jul 12 '15 at 15:45
  • 2
    Also, some editors (vim being one of them) has the ability to coerce tabs into spaces. If your editor has that ability, I'd recommend turning it on. – NightShadeQueen Jul 12 '15 at 15:45
  • You may have a mixture of spaces and tabs. In order to fix this, open the file in IDLE shell. Then, select everything and click on Format in the menu bar. Click on Untabify region and make sure that you are doing it to 4 columns. If this doesn't work, you might have a syntax error earlier in your code – rassa45 Jul 12 '15 at 16:00
  • @AvinashRaj Which method name you mean? It may be by accident. – Léo Léopold Hertz 준영 Jul 12 '15 at 16:07

2 Answers2

1

The line with cursor.close() has a tab in it, and the preceding ones have only leading spaces. This breaks the indentation.

A good solution is to replace all tabs by four spaces.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
0

To replace tabs by four spaces you can modify your file with sed:

sed -ir 's/\t/    /g' python_w_tabs.py

This will modify your file in place, but if you want to validate before overwriting try:

cat python_w_tabs.py | sed -r 's/\t/    /g' > python_wo_tabs.py

Also, this is with gnu sed, so it might be different if you're on a mac, and I don't know for windows.

fivetentaylor
  • 1,277
  • 7
  • 11