Python IndentationError:意外的缩进错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3920628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IndentationError: unexpected indent error
提问by ian
I am new to Python and am getting this error:
我是 Python 新手,并且收到此错误:
Traceback (most recent call last):
File "/usr/local/bin/scrapy", line 4, in <module>
execute()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy/cmdline.py", line 130, in execute
_run_print_help(parser, _run_command, cmd, args, opts)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy/cmdline.py", line 96, in _run_print_help
func(*a, **kw)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy/cmdline.py", line 136, in _run_command
cmd.run(args, opts)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy/commands/crawl.py", line 42, in run
q = self.crawler.queue
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy/command.py", line 31, in crawler
self._crawler.configure()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy/crawler.py", line 36, in configure
self.spiders = spman_cls.from_settings(self.settings)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy/spidermanager.py", line 33, in from_settings
return cls(settings.getlist('SPIDER_MODULES'))
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy/spidermanager.py", line 23, in __init__
for module in walk_modules(name):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scrapy/utils/misc.py", line 65, in walk_modules
submod = __import__(fullpath, {}, {}, [''])
File "/my_crawler/empt/empt/spiders/empt_spider.py", line 59
check_exists_sql = "SELECT * FROM LINKS WHERE link = '%s' LIMIT 1" % item['link']
^
IndentationError: unexpected indent
On this bit of code:
在这段代码上:
def parse_item(self, response):
hxs = HtmlXPathSelector(response)
sites = hxs.select('//a[contains(@href, ".mp3")]/@href').extract()
items = [ ]
#for site in sites:
#link = site.select('a/@href').extract()
#print site
for site in sites:
item = EmptItem()
item['link'] = site #site.select('a/@href').extract()
#### DB INSERT ATTEMPT ###
#MySQL Test
#open db connection
db = MySQLdb.connect("localhost","root","str0ng","TESTDB")
#prepare a cursor object using cursor() method
cursor = db.cursor()
#see if any links in the DB match the crawled link
check_exists_sql = "SELECT * FROM LINKS WHERE link = '%s' LIMIT 1" % item['link']
cursor.execute(check_exists_sql)
if cursor.rowcount = 0:
#prepare SQL query to insert a record into the db.
sql = "INSERT INTO LINKS ( link ) VALUES ( '%s')" % item['link']
try:
#execute the sql command
cursor.execute(sql)
#commit your changes to the db
db.commit()
except:
#rollback on error
db.rollback()
#fetch a single row using fetchone() method.
#data = cursor.fetchone()
#print "Database version: %s " % data
#disconnect from server
db.close()
### end mysql
items.append(item)
return items?
采纳答案by Johnsyweb
While the indentation errors are obvious in the StackOverflow page, they may not be in your editor. You have a mix of different indentation types here, 1, 4 and 8 spaces. You should always use four spaces for indentation, as per PEP8. You should also avoid mixing tabs and spaces.
虽然缩进错误在 StackOverflow 页面中很明显,但它们可能不在您的编辑器中。这里混合了不同的缩进类型,1、4 和 8 个空格。根据PEP8,您应该始终使用四个空格进行缩进。您还应该避免混合使用制表符和空格。
I also recommend that you try to run your script using the '-tt' command-line optionto determine when you accidentally mix tabs and spaces. Of course any decent editor will be able to highlight tabs versus spaces (such as Vim's 'list'option).
我还建议您尝试使用' -tt' 命令行选项运行脚本,以确定何时不小心混合了制表符和空格。当然,任何体面的编辑器都可以突出显示制表符与空格(例如Vim 的'list'option)。
回答by kindall
The indentation is wrong, as the error tells you. As you can see, you have indented the code beginning with the indicated line too little to be in the forloop, but too much to be at the same level as the for loop. Python sees the lack of indentation as ending the forloop, then complains you have indented the rest of the code too much. (The defline I'm betting is just an artifact of how Stack Overflow wants you to format your code.)
正如错误告诉您的那样,缩进是错误的。如您所见,以指定行开头的代码缩进太少而无法进入for循环,但缩进太多以至于无法与 for 循环处于同一级别。Python 将缺少缩进视为结束for循环,然后抱怨您对其余代码的缩进太多了。(def我打赌的那条线只是 Stack Overflow 想让你格式化代码的产物。)
Edit:Given your correction, I'm betting you have a mixture of tabs and spaces in the source file, such that it looks to the human eye like the code lines up, but Python considers it not to. As others have suggested, using only spaces is the recommended practice (see PEP 8). If you start Python with python -t, you will get warnings if there are mixed tabs and spaces in your code, which should help you pinpoint the issue.
编辑:鉴于您的更正,我敢打赌您在源文件中混合了制表符和空格,这样它在人眼中看起来就像代码排列一样,但 Python 认为不是。正如其他人所建议的,只使用空格是推荐的做法(参见PEP 8)。如果您使用 启动 Python python -t,如果您的代码中混合了制表符和空格,您将收到警告,这应该有助于您查明问题。
回答by Chris Bunch
The error is pretty straightforward - the line starting with check_exists_sqlisn't indented properly. From the context of your code, I'd indent it and the following lines to match the line before it:
错误非常简单 - 开头的行check_exists_sql没有正确缩进。从您的代码的上下文中,我会缩进它和以下几行以匹配它之前的行:
#open db connection
db = MySQLdb.connect("localhost","root","str0ng","TESTDB")
#prepare a cursor object using cursor() method
cursor = db.cursor()
#see if any links in the DB match the crawled link
check_exists_sql = "SELECT * FROM LINKS WHERE link = '%s' LIMIT 1" % item['link']
cursor.execute(check_exists_sql)
And keep indenting it until the forloop ends (all the way through to and including items.append(item).
并继续缩进直到for循环结束(一直到并包括items.append(item).
回答by Anurag Uniyal
As the error says you have not correctly indented code, check_exists_sqlis not aligned with line above it cursor = db.cursor().
由于错误表明您没有正确缩进代码,check_exists_sql未与其上方的行对齐cursor = db.cursor()。
Also use 4 spaces for indentation.
还使用 4 个空格进行缩进。
Read this http://diveintopython.net/getting_to_know_python/indenting_code.html
阅读这个http://diveintopython.net/getting_to_know_python/indenting_code.html

