I am making a Python program which checks if my server is up. If it isn't, it will tweet, saying that it's down. It will then go on to tweet when it comes back up.
But when I run my code I get this error:
File "Tweet_bot.py", line 31
textfile = open('/root/Documents/server_check.txt','w')
^
IndentationError: unexpected indent
My code for the broken section is below:
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
You are mixing tabs and spaces:
>>> 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')"]
Note the \t
at the start of the second line, but the first has 4 spaces instead.
Python expands tabs to the next 8th column, which is more than the 4 spaces in the first line. So that second line is indented to two indentation levels, while the first is only indented one level.
The Python style guide, PEP 8 recommends you use spaces only:
Spaces are the preferred indentation method.
and
Python 2 code indented with a mixture of tabs and spaces should be converted to using spaces exclusively.
as getting your tabs configured correctly and not accidentally muck up indentation by mixing in a few spaces is hard.
Configure your editor to convert tabs to spaces when you edit; that way you can still use the TAB keyboard key without falling into this trap.