Error always on line 102 of my code - python

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.

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.

Python ValueError: chr() arg not in range(256)

So I am learning python and redoing some old projects. This project involves taking in a dictionary and a message to be translated from the command line, and translating the message. (For example: "btw, hello how r u" would be translated to "by the way, hello how are you".
We are using a scanner supplied by the professor to read in tokens and strings. If necessary I can post it here too. Heres my error:
Nathans-Air-4:py1 Nathan$ python translate.py test.xlt test.msg
Traceback (most recent call last):
File "translate.py", line 26, in <module>
main()
File "translate.py", line 13, in main
dictionary,count = makeDictionary(commandDict)
File "/Users/Nathan/cs150/extra/py1/support.py", line 12, in makeDictionary
string = s.readstring()
File "/Users/Nathan/cs150/extra/py1/scanner.py", line 105, in readstring
return self._getString()
File "/Users/Nathan/cs150/extra/py1/scanner.py", line 251, in _getString
if (delimiter == chr(0x2018)):
ValueError: chr() arg not in range(256)
Heres my main translate.py file:
from support import *
from scanner import *
import sys
def main():
arguments = len(sys.argv)
if arguments != 3:
print'Need two arguments!\n'
exit(1)
commandDict = sys.argv[1]
commandMessage = sys.argv[2]
dictionary,count = makeDictionary(commandDict)
message,messageCount = makeMessage(commandMessage)
print(dictionary)
print(message)
i = 0
while count < messageCount:
translation = translate(message[i],dictionary,messageCount)
print(translation)
count = count + 1
i = i +1
main()
And here is my support.py file I am using...
from scanner import *
def makeDictionary(filename):
fp = open(filename,"r")
s = Scanner(filename)
lyst = []
token = s.readtoken()
count = 0
while (token != ""):
lyst.append(token)
string = s.readstring()
count = count+1
lyst.append(string)
token = s.readtoken()
return lyst,count
def translate(word,dictionary,count):
i = 0
while i != count:
if word == dictionary[i]:
return dictionary[i+1]
i = i+1
else:
return word
i = i+1
return 0
def makeMessage(filename):
fp = open(filename,"r")
s = Scanner(filename)
lyst2 = []
string = s.readtoken()
count = 0
while (string != ""):
lyst2.append(string)
string = s.readtoken()
count = count + 1
return lyst2,count
Does anyone know whats going on here? I've looked through several times and i dont know why readString is throwing this error... Its probably something stupid i missed
chr(0x2018) will work if you use Python 3.
You have code that's written for Python 3 but you run it with Python 2. In Python 2 chr will give you a one character string in the ASCII range. This is an 8-bit string, so the maximum parameter value for chris 255. In Python 3 you'll get a unicode character and unicode code points can go up to much higher values.
The issue is that the character you're converting using chr isn't within the range accepted (range(256)). The value 0x2018 in decimal is 8216.
Check out unichr, and also see chr.

Cannot concatenate 'str' and 'Nontype' objects error despite all arguments being pure string

I'm writing this python program and I'm getting this really confusing error in random. Here's part of my script:
Part of code in ai.py (starting at line #133)
elif (config.var0 < config.var1):
message = "SUCCESS_0021! var0 successfully adjusted."
print message
aux_func.write_log(message)
config.var0 = float(config.var1)
config.ask_trail = (1.0 + config.var2) * config.var3
The write_log function in aux_func.py file looks like this starting line #43
def write_log (message):
log_file = open(current_dir + '//logs//' + date_stamp(), 'a+')
temp_write = "\n " + time_stamp() + " : " + str(message)
log_file.write(temp_write)
log_file.close()
This works just fine and writes log file as expected most of the times. But, when I run this script for a while, then the console has this weird message that says:
Traceback <most recent call last):
File "main1.py", line 102, in <module>
func_flag = ai.decide()
File "C:\project\ai.py", line 137, in task_decide
aux_func.write_log(message)
File "C:\project\aux_func.py", line 45, in write_log
temp_write = "\n " + time_stamp() + " : " + str(message)
TypeError: cannot concatenate 'str' and 'NoneType' objects
The ai.py function is called from main1.py function.
I don't understand this error and I have banged my head against the wall to try and understand why I get this. The message is perfectly a string and I don't see any 'NoneType' objects in my the code where the error is being shown.
EDIT: Sorry, forgot to give you the time_stamp() code, here you go:
def time_stamp():
flag = 0
current_time = ''
system_date_time = str (datetime.datetime.now())
while (system_date_time == None):
system_date_time = str (datetime.datetime.now())
for c in system_date_time:
if (c == ' '):
flag = 1
if (c != '.'):
if (flag == 1):
current_time += c
else:
pass
else:
return current_time
It is the time_stamp() callable; it returns None.
Nothing else on that line could be None as they are either string literals, or the result of the str() function:
temp_write = "\n " + time_stamp() + " : " + str(message)
hence, the only remaining candidate is time_stamp().

KeyError: 'fullcount' in mail script

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.

Python:winreg module :Windows 7:None is not valid HKEY error

I ran into issues while reading registry value for windows 7 winth winreg module .Any pointers to resolve the same?
Code :
try:
ParentKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall")
i = 0
while 1:
name, value, type = _winreg.EnumValue(ParentKey, i)
print repr(name),
i += 1
except Exception as e:
print(Exception(e))
ParentKey =_winreg.DisableReflectionKey(ParentKey)
temp = _winreg.QueryValueEx(ParentKey, 'DisplayName')
temp1 = _winreg.QueryValueEx(ParentKey, 'DisplayVersion')
temp2 = _winreg.QueryValueEx(ParentKey, 'Publisher')
temp3 = _winreg.QueryValueEx(ParentKey, 'InstallLocation')
display = str(temp[0])
display_ver=str(temp1[0])
display_p=str(temp2[0])
display_loc=str(temp3)
print ('Display Name: ' + display + '\nDisplay version: ' + display_ver + '\nVendor/Publisher: ' + display_p +'\nRegkey: ' + display_loc +'\nInstall Location: ' )
Output:
[Error 259] No more data is available
Traceback (most recent call last):
File "C:\Users\Test\workspace\Pythontests\src\test.py", line 24, in <module>
temp = _winreg.QueryValueEx(ParentKey, 'DisplayName')
TypeError: None is not a valid HKEY in this context
**strong text**
This line:
ParentKey = _winreg.DisableReflectionKey(ParentKey)
will return None. The function DisableReflectionKey is not documented as returning anything (success or failure is indicated by whether or not an exception is raised). Such a function that does not return anything returns None implicitly. Since you bind the returned value to ParentKey, that variable will holds None from that point on.
So, of course the subsequent call,
_winreg.QueryValueEx(ParentKey, 'DisplayName')
will fail since QueryValueEx requires a defined key (not None) to work.

Categories

Resources