代码
#!/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()
但我明白了
File "9.7.2015.py", line 14
cursor.close()
^
IndentationError: unexpected indent
这很奇怪,因为我似乎没有任何缩进问题。
您如何应对如此意外的缩进挑战?
带有
cursor.close()
的行中有一个制表符,前面的行只有前导空格。这打破了缩进。
一个好的解决方案是将所有制表符替换为四个空格。
要将制表符替换为四个空格,您可以使用 sed 修改文件:
sed -ir 's/\t/ /g' python_w_tabs.py
这将就地修改您的文件,但如果您想在覆盖之前进行验证,请尝试:
cat python_w_tabs.py | sed -r 's/\t/ /g' > python_wo_tabs.py
另外,这是使用 gnu sed 进行的,所以如果你使用的是 Mac,情况可能会有所不同,我不知道 Windows 上的情况。