如何处理 Python 中的意外缩进错误
How to handle unexpected indent error in Python
代码
#!/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。
代码
#!/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。