KeyError: 'fullcount' in mail script - python

I wrote a Python script to check my email and turn on an LED when I have new mail.
After about 1 hour, I got the error:
Traceback (most recent call last):
File "checkmail.py", line 10, in <module>
B = int(feedparser.parse("https://" + U + ":" + P + "#mail.google.com/gmail/feed/atom")["feed"]["fullcount"])
File "/usr/local/lib/python2.7/dist-packages/feedparser.py", line 375, in __getitem__
return dict.__getitem__(self, key)
KeyError: 'fullcount'
I looked here
and didn't find an answer. Here is my code:
#!/usr/bin/env python
import RPi.GPIO as GPIO, feedparser, time
U = "username"
P = "password"
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
A = 23
GPIO.setup(A, GPIO.OUT)
while True:
B = int(feedparser.parse("https://" + U + ":" + P + "#mail.google.com/gmail/feed/atom")["feed"]["fullcount"])
if B > 0:
GPIO.output(A, True)
else:
GPiO.output(A, False)
time.sleep(60)
I'm running this on a Raspberry Pi.
Thanks in advance for any help.

You need to add some debug code and see what this call returns:
feedparser.parse("https://" + U + ":" + P + "#mail.google.com/gmail/feed/atom")["feed"]
It's clearly something that does not contain a "fullcount" item. You might want to do something like this:
feed = feedparser.parse("https://{}:{}#mail.google.com/gmail/feed/atom".format(U, P))
try:
B = int(feed["feed"]["fullcount"])
except KeyError:
# handle the error
continue # you might want to sleep or put the following code in the else block
That way you can deal with the error (you might want to catch ValueError too, in case int() fails because of an invalid value) without it blowing up your script.

Related

string index out of range? - python

im buliding a chat and i'm keep getting the next error:
Traceback (most recent call last):
File "C:/Users/ronen/Documents/CyberLink/tryccc.py", line 651, in <module>
main()
File "C:/Users/ronen/Documents/CyberLink/tryccc.py", line 630, in main
print_message(data_from_server, len(temp_message), username)
File "C:/Users/ronen/Documents/CyberLink/tryccc.py", line 265, in print_message
temp_l = data[0]
IndexError: string index out of range
i am trying to get the first char of the data string and convert it into int but i get this error
the problem is in the first line of the code
def print_message(d_temp, line_length, this_username):
temp_l = d_temp[0] #the problematic line
len_username = int(temp_l)
username_sender = d_temp[1:(len_username + 1)]
message_sent = d_temp[(len_username + 1): -4]
hour_time = d_temp[-4: -2]
min_time = d_temp[-2:]
printed_message = "\r" + hour_time + ":" + min_time + " " + username_sender + " : " + message_sent
print printed_message, # Prints this message on top of what perhaps this client started writing.
# if this client started typing message
complete_line_with_space(len(printed_message), line_length)
data- the data (string) from the server
line_length - the length of the temp massage
this_username - the client's username
thank you to all the helpers
empty d_temp will give this error.
This might be the reason:
>>> d_temp = ""
>>> d_temp[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
This happens because print_message is executed with an empty string as first parameter
print_message("",...)
This means the problem is somewhere else in your code.

how i can send more than 2 arguments on telnet session in python?

I have two lists that have user name and password. I want to check which one is correct by iterating through two zipped lists but it isn't working.
Below is the traceback
Traceback (most recent call last):
File "C:\Users\mohamed\Downloads\second_PassWD_Test.py", line 27, in <module>
mme=tn.write(j,i)
TypeError: write() takes exactly 2 arguments (3 given)
Below is the code throwing the exception.
import telnetlib
import re
HOST = "192.168.1.1"
USER = ["admin\n","admin\n","admin"]
PASS = ["cpe#","1234"," "]
try:
tn = telnetlib.Telnet(HOST)
except:
print "Oops! there is a connection error"
frist_log = tn.read_until(":")
if "log" in frist_log:
while 1:
for i,j in zip(USER,PASS):
tn.write(j,i)
break
Telnet.write(buffer) only takes two arguments first is the telnet object and the other is a buffer to send to your session, hence your solution will throw an exception. One way to solve the problem is like a except script using the expect api and use a list of expected output as shown in example below
USER = ["admin\n","admin\n","admin"]
PASS = ["cpe#","1234"," "]
prompt = "#" ## or your system prompt
tn = telnetlib.Telnet(HOST)
first_log = tn.read_until(":")
for user,password in zip(USER,PASS):
try:
tn.write(user)
tn.expect([":"],timeout = 3) # 3 second timeout for password prompt
tn.write(password+"\n")
index,obj,string = tn.expect([":",prompt],timeout = 3)
found = string.find(prompt)
if found >= 0:
break # found the username password match break
###else continue for next user/password match
except:
print "exception",sys.exc_info()[0]

Python pyparsing issue

I am very new to python and using pyparsing but getting some exception with following code
while site_contents.find('---', line_end) != line_end + 2:
cut_start = site_contents.find(" ", site_contents.find("\r\n", start))
cut_end = site_contents.find(" ", cut_start+1)
line_end = site_contents.find("\r\n", cut_end)
name = site_contents[cut_start:cut_end].strip()
float_num = Word(nums + '.').setParseAction(lambda t:float(t[0]))
nonempty_line = Literal(name) + Word(nums+',') + float_num + Suppress(Literal('-')) + float_num * 2
empty_line = Literal(name) + Literal('-')
line = nonempty_line | empty_line
parsed = line.parseString(site_contents[cut_start:line_end])
start = line_end
Exception
Traceback (most recent call last):
File "D:\Ecllipse_Python\HellloWorld\src\HelloPython.py", line 108, in <module>
parsed = line.parseString(site_contents[cut_start:line_end]) # parse line of data following cut name
File "C:\Users\arbatra\AppData\Local\Continuum\Anaconda\lib\site-packages\pyparsing.py", line 1041, in parseString
raise exc
pyparsing.ParseException: Expected W:(0123...) (at char 38), (line:1, col:39)
how to resolve this issue?
You'll get a little better exception message if you give names to your expressions, using setName. From the "Expected W:(0123...)" part of the exception message, it looks like the parser is not finding a numeric value where it is expected. But the default name is not showing us enough to know which type of numeric field is expected. Modify your parser to add setName as shown below, and also change the defintion of nonempty_line:
float_num = Word(nums + '.').setParseAction(lambda t:float(t[0])).setName("float_num")
integer_with_commas = Word(nums + ',').setName("int_with_commas")
nonempty_line = Literal(name) + integer_with_commas + float_num + Suppress(Literal('-')) + float_num * 2
I would also preface the call to parseString with:
print site_contents[cut_start:line_end]
at least while you are debugging. Then you can compare the string being parsed with the error message, including the column number where the parse error is occurring, as given in your posted example as "(at char 38), (line:1, col:39)". "char xx" starts with the first character as "char 0"; "col:xx" starts with the first column as "col:1".
These code changes might help you pinpoint your problem:
print "12345678901234567890123456789012345678901234567890"
print site_contents[cut_start:line_end]
try:
parsed = line.parseString(site_contents[cut_start:line_end])
except ParseException as pe:
print pe.loc*' ' + '^'
print pe
Be sure to run this in a window that uses a monospaced font (so that all the character columns line up, and all characters are the same width as each other).
Once you've done this, you may have enough information to fix the problem yourself, or you'll have some better output to edit into your original question so we can help you better.

Python - NameError

I have the following code that uses 3 strings 'us dollars','euro', '02-11-2014',
and a number to calculate the exchange rate for that given date. I modified the
code to pass those arguments but I get an error when I try to call it with
python currencyManager.py "us dollars" "euro" 100 "02-11-2014"
Traceback (most recent call last):
File "currencyManager.py", line 37. in <module>
currencyManager(currTo,currFrom,currAmount,currDate)
NameError: name 'currTo' is not defined
I'm fairly new to Python so my knowledge is limited. Any help would be greatly appreciated. Thanks.
Also the version of Python I'm using is 3.4.2.
import urllib.request
import re
def currencyManager(currTo,currFrom,currAmount,currDate):
try:
currency_to = currTo #'us dollars'
currency_from = currFrom #'euro'
currency_from_amount = currAmount
on_date = currDate # Day-Month-Year
currency_from = currency_from.replace(' ', '+')
currency_to = currency_to.replace(' ', '+')
url = 'http://www.wolframalpha.com/input/?i=' + str(currency_from_amount) + '+' + str(currency_from) + '+to+' + str(currency_to) + '+on+' + str(on_date)
req = urllib.request.Request(url)
output = ''
urllib.request.urlopen(req)
page_fetch = urllib.request.urlopen(req)
output = page_fetch.read().decode('utf-8')
search = '<area shape="rect.*href="\/input\/\?i=(.*?)\+.*?&lk=1'
result = re.findall(r'' + search, output, re.S)
if len(result) > 0:
amount = float(result[0])
print(str(amount))
else:
print('No match found')
except URLError as e:
print(e)
currencyManager(currTo,currFrom,currAmount,currDate)
The command line
python currencyManager.py "us dollars" "euro" 100 "02-11-2014"
does not automatically assign "us dollars" "euro" 100 "02-11-2014" to currTo,currFrom,currAmount,currDate.
Instead the command line arguments are stored in a list, sys.argv.
You need to parse sys.argv and/or pass its values on to the call to currencyManager:
For example, change
currencyManager(currTo,currFrom,currAmount,currDate)
to
import sys
currencyManager(*sys.argv[1:5])
The first element in sys.argv is the script name. Thus sys.argv[1:5] consists of the next 4 arguments after the script name (assuming 4 arguments were entered on the command line.) You may want to check that the right number of arguments are passed on the command line and that they are of the right type. The argparse module can help you here.
The * in *sys.argv[1:5] unpacks the list sys.argv[1:5] and passes the items in the list as arguments to the function currencyManager.

Error always on line 102 of my code

So I am creating a module, and I am importing it to a python shell and running some stuff to make sure all features work and such.
For some reason every time I run the code, it gives the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
#anything can be here
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
So where the #anything can be here is, is whatever is on line 102 of my code. Originally line 102 was:
if isinstance(startindex,datetime.datetime):
and I got the error above. I put a quick print statement on line 102 to check and it gave the same error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
print 'Hello'
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
Is this some sort of bug? Why is it telling me there is an error with datetime on the line print 'Hello'?
Because it may be helpful, I will give you the function I am having trouble with since I have no clue how this is possible. I am keeping the print 'Hello' line so you can see where line 102 is:
def url_maker(latitudes,longitudes,times=None,color='red',label=' ',zoom=12,center=None,start=None,end=None,by=None,size='600x300'):
urls = []
import datetime
if isinstance(times[0],str) or isinstance(times[0],datetime.datetime):
from dateutil import parser
if isinstance(times[0],str):
times = [parser.parse(x) for x in times]
if isinstance(start,str):
startindex = parser.parse(start)
else:
startindex = start
if isinstance(end,str):
endindex = parse.parse(end)
else:
endindex = end
print 'Hello'
if isinstance(startindex,datetime.datetime):
startpos = between_times(times,startindex,by='start')
elif isinstance(startindex,int):
if isinstance(endindex,datetime.datetime):
startpos = between_times(times,endindex,by='end') - start
else:
startpos = start
else:
pass
if isinstance(endindex,datetime.datetime):
endpos = between_times(times,endindex,by='end')
elif isinstance(endindex,int):
if isinstance(startindex,datetime.datetime):
endpos = between_times(times,startindex,by='start') + end
else:
endpos = end
else:
pass
else:
times = range(1,len(latitudes) + 1)
if isinstance(start,int):
startpos = start
else:
startpos = None
if isinstance(end,int):
endpos = end
else:
endpos = None
if isinstance(by,str):
lat,lon,t = latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print lat
t,lats,lons = time_sample(t,by,lat,lon)
elif isinstance(by,int):
lats,lons,t = latitudes[startpos:endpos:by],latitudes[startpos:endpos:by],times[startpos:endpos:by]
else:
lats,lons,t= latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print t
print len(t)
if center == None:
latit = [str(i) for i in lats]
longi = [str(i) for i in lons]
center = '&center=' + common_finder(latit,longi)
else:
center = '&center=' + '+'.join(center.split())
zoom = '&zoom=' + str(zoom)
for i in range(len(lats)):
#label = str(i)
x,y = str(lats[i]),str(lons[i])
marker = '&markers=color:' + color + '%7Clabel:' + label + '%7C' + x + ',' + y
url = 'http://maps.googleapis.com/maps/api/staticmap?maptype=roadmap&size=' + size + zoom + center + marker + '&sensor=true'
urls.append(url)
#print i
return urls,t
You are running with a stale bytecode cache or are re-running the code in an existing interpreter without restarting it.
The traceback code has only bytecode to work with, which contains filename and linenumber information. When an exception occurs, the source file is loaded to retrieve the original line of code, but if the source file has changed, that leads to the wrong line being shown.
Restart the interpreter and/or remove all *.pyc files; the latter will be recreated when the interpreter imports the code again.
As for your specific exception; you probably imported the datetime class from the datetime module somewhere:
from datetime import datetime
The datetime class does not have a datetime attribute, only the module does.

Categories

Resources