我正在制作一个python程序,检查我的服务器是否已启动,如果不是,它会发推文说它已关闭。然后它会在重新启动时继续发推。
但是当我运行我的代码时,我收到了这个错误:
File "Tweet_bot.py", line 31
textfile = open('/root/Documents/server_check.txt','w')
^
IndentationError: unexpected indent
我的破碎部分代码如下:
try :
response = urlopen( url )
except HTTPError, e:
tweet_text = "Raspberry Pi server is DOWN!"
textfile = open('/root/Documents/server_check.txt','w')
textfile.write("down")
textfile.close()
except URLError, e:
tweet_text = "Raspberry Pi server is DOWN!"
textfile = open('/root/Documents/server_check.txt','w')
textfile.write("down")
textfile.close()
else :
html = response.read()
if textfile = "down":
tweet_text = "Raspberry Pi server is UP!"
textfile = open('/root/Documents/server_check.txt','w')
textfile.write("up")
textfile.close()
if textfile = "up":
tweet_text = ""
pass
if len(tweet_text) <= 140 and tweet_text > 0:
api.update_status(status=tweet_text)
else:
pass
答案 0 :(得分:3)
您正在混合制表符和空格:
>>> from pprint import pprint
>>> pprint('''
... tweet_text = "Raspberry Pi server is DOWN!"
... textfile = open('/root/Documents/server_check.txt','w')
... '''.splitlines())
['',
' tweet_text = "Raspberry Pi server is DOWN!"',
"\ttextfile = open('/root/Documents/server_check.txt','w')"]
注意第二行开头的\t
,但第一行有4个空格。
Python将标签扩展到下一个第8列,这超过了第一行中的4个空格。因此第二行缩进为两个缩进级别,而第一行只缩进一级。
Python style guide, PEP 8建议您仅使用空格 :
空格是首选的缩进方法。
和
使用制表符和空格的混合缩进的Python 2代码应该转换为仅使用空格。
因为正确配置标签并且不会因为在几个空格中混合而意外地弄乱缩进很难。
配置编辑器以在编辑时将制表符转换为空格;这样你仍然可以使用 TAB 键盘键,而不会陷入此陷阱。