我正在制作一个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
您正在混合制表符和空格:
>>> 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 个空格多。因此,第二行缩进到 two 缩进级别,而第一行仅缩进一级。
Python 风格指南,PEP 8 建议您仅使用空格:
空格是首选的缩进方法。和
混合使用制表符和空格缩进的Python 2代码应转换为仅使用空格。
因为正确配置选项卡并且不意外地通过混合几个空格来弄乱缩进是很困难的。
配置编辑器在编辑时将制表符转换为空格;这样你仍然可以使用
TAB键盘键而不会陷入这个陷阱。