I have the following code:
from yahoo_finance import Currency
symbolslist = ["EURUSD","EURGBP","EURJPY","EURRUB","USDCAD","USDCHF","AUSUSD"]
for i in range(len(symbolslist)):
symbol = symbolslist[i]
nomisma = Currency(symbol).get_rate()
quota = symbol + " = " + nomisma
print quota
And I get the result:
EURUSD = 1.0891
EURGBP = 0.7322
EURJPY = 129.7440
EURRUB = 63.0560
USDCAD = 1.2614
USDCHF = 0.9622
Traceback (most recent call last):
File "yahoopy.py", line 13, in <module>
quota = symbol + " = " + nomisma
TypeError: cannot concatenate 'str' and 'NoneType' objects
I'm aware that this error has been talked about in this link.
But I was hoping that I could overcome this bug without resorting to mysql.
The problem is a typo. Instead of AUDUSD you wrote AUSUSD. Fix it and the error will be gone:
symbolslist = ["EURUSD","EURGBP","EURJPY","EURRUB","USDCAD","USDCHF","AUDUSD"]
Still it is a good idea to use format as #BhargavRao suggested to catch such bugs.
Add an if clause above your concat statement
if nomisma:
quota = symbol + " = " + nomisma
Assumption - It means that AUSUSD is not present in your database, that is why Currency(symbol).get_rate() is returning None. Also as mentioned here it is AUDUSD and not AUSUSD
Note : It is better to use format to concat as in
quota = "{} = {}".format(symbol,nomisma)
Related
(Ignoring that g.text and p.content return "You're not authorised to view this content" from plug.dj) I get the error
Traceback (most recent call last):
File "plugling.py", line 20, in <module>
r.send('{"a":"auth","p":"'+g+'","t":'+t+'}')
TypeError: cannot concatenate 'str' and 'Response' objects
When running this code:
import time
from websocket import create_connection
import requests
import calendar
slug = 'sfoc'
r = create_connection("wss://godj.plug.dj/socket")
t = calendar.timegm(time.gmtime())
token = 'https://plug.dj/_/auth/token'
join = 'https://plug.dj/_/rooms/join'
pl = {'slug': 'sfoc'}
g = requests.get(token)
print g.text
p = requests.post(join, data=pl)
print p.content
r.send('{"a":"auth","p":"'+g+'","t":'+t+'}')
result = r.recv()
print result
r.close()
It didn't like me using %s for the variables either. I don't know what I'm doing wrong. Thanks in advance and let me know if I haven't explained something clearly.
You are trying to concatenate a Response object:
g = requests.get(token)
# ...
r.send('{"a":"auth","p":"'+g+'","t":'+t+'}')
g is the response object. You wanted to get the text value:
r.send('{"a": "auth", "p": "' + g.text + '", "t":' + t + '}')
You may want to look at the json module if you are trying to send JSON data there:
r.send(json.dumps({'a': 'auth', 'p': g.text, 't': t}))
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.
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().
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 = '¢er=' + common_finder(latit,longi)
else:
center = '¢er=' + '+'.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.
Please I am beginner in python coding.This is my code and am not able to resolve the error . Can some one suggest me what is the prob in code actually. thanks in advance.
import urllib2
username = '<YOUR USERNAME>'
password = '<YOUR PASSWORD>'
format = 'json' # json or xml
filename = 'archive.json' # filename of the archive
tweets = 164 # number of tweets
pages = (int(float(tweets)/float(80)))+1
auth = urllib2.HTTPPasswordMgrWithDefaultRealm()
auth.add_password(None, 'http://twitter.com/account/', username, password)
authHandler = urllib2.HTTPBasicAuthHandler(auth)
opener = urllib2.build_opener(authHandler)
urllib2.install_opener(opener)
i = 1
response = ''
print 'Downloading tweets. Note that this may take some time'
while i <= pages:
request = urllib2.Request('http://twitter.com/statuses/user_timeline/account.' \
+ format + '?page=' + str(i))
response = response + urllib2.urlopen(request).read()
i = i + 1
handle = open(filename,"w")
handle.write(response)
handle.close()
print 'Archived ' + str(tweets) + ' of ' + username + \
'\'s tweets to ' + filename
ERROR is like this below:
**Traceback (most recent call last):
File "<pyshell#14>", line 3, in <module>
+ format + '?page=' + str(i))
TypeError: cannot concatenate 'str' and 'builtin_function_or_method' objects**
format is a built-in function. The error you quote is exactly what you get if you try to use + with the built-in format and a string.
Your earlier assignment format = 'json' should have shadowed the built-in function. But your error trace indicates that you're running this from some sort of shell, and not actually executing the code as you have posted it. So without knowing what exactly is executing, my guess is your assignment to format isn't in effect, for whatever reason.