Basically trying to modify the this tutorial for Currency's instead of
stocks: http://pythonprogramming.net/advanced-matplotlib-graphing-charting-tutorial/
with my current code I get:
Error: main loop can only concatenate tuple (not "str") to tuple
The code:
import urllib2
import time
CurrencysToPull = 'audusd','eurusd','usdcad'
def pullData(Currency):
try:
fileline = Currency+'.txt'
urlToVisit = 'http://finance.yahoo.com/echarts?s=Currency=X#{"allowChartStacking":true}/'+Currency+'/chartdata;type=quote:range=1y/csv'
sourcecode = urllib2.urlopen(urlToVisit).read()
splitSource = sourcecode.split('\n')
for eachLine in splitSource:
splitLine = eachLine.split(',')
if len(splitLine)==6:
if 'valuse' not in eachLine:
saveFile = open(fileLine,'a')
lineToWrite = eachLine+'\n'
saveFile.write(lineToWrite)
print 'Pulled', Currency
print 'sleeping'
time.sleep(1)
except Exception,(e):
print('main loop'), str(e)
for eachStock in CurrencysToPull:
pullData(CurrencysToPull)
You are passing in the CurrencysToPull tuple to your function:
for eachStock in CurrencysToPull:
pullData(CurrencysToPull)
which you then try to concatenate a string to:
fileline = Currency+'.txt'
You probably meant to pass in eachStock instead:
for eachStock in CurrencysToPull:
pullData(eachStock)
The error is in this line :
fileline = Currency+'.txt'
Currency is a tuple, .txt is a string
In your for loop you are passing CurrencysToPull instead of eachStock.
it should be:
for eachStock in CurrencysToPull:
You could have got better information about the errors using traceback in your exception handling.
except Exception,(e):
print('main loop'), str(e)
print(traceback.format_exc())
Related
I have this text file:
this is name_of_liquid(string)=amount(int)
liquid1=200
liquid2=20
liquid_X_= empty
liquid_3= 3000
now, the name does not really matter however the amount does. It has to be an int.
If it is any other type beside int the program would raise an exception
Here is my code/ pseudocode:
#opening the file
d={}
try:
dic = {}
with open('accounts.txt') as f:
for line in f:
(key , val) = line.split()
d[key] = int(val)
#except ValueError:
# print('The value for', key,'is', value,' which is not a number!')
the except block is commented because that is my pseudocode and how I planed in handling the
error, but when I run this code without using exception handling, I get an error of 'not enough values to unpack'
Can anyone please help me?
Try this
f = open("acounts.txt", "r")
dict = {}
try:
for line in f:
line = line.split("=")
dict[line[0]] = int(line[1])
except:
print("Invalid value for key.")
You should split the lines with = as delimiter and strip the list to get rid of extra whitespaces.
I personally think that the try catch block should be used while adding elements to the dictionary.
The following code should work for your problem.
d = {}
with open('accounts.txt', 'r') as f:
for line in f:
(key , val) = map(str.strip,line.split("="))
try:
d[key] = int(val)
except ValueError:
print('The value for', key,'is', val,' which is not a number!')
I'm currently creating a programming language in Python 3.6 and for some reason, the following code produces an IndexError: string index out of range.
When I try to execute the following code in a Windows Batch File:
#echo off
python run-file.py test.ros
pause
But I'm getting the following output:
Traceback (most recent call last):
File "run-file.py", line 16, in <module>
if not(value[1][0] == "!") and ignoreline == False:
IndexError: string index out of range
Press any key to continue . . .
The run-file.py file looks like this:
from sys import argv as args
from sys import exit as quit
import syntax
try:
args[1]
except IndexError:
print("ERROR: No ROS Code file provided in execution arguments")
print("Ensure the execution code looks something like this: python run-file.py test.ros")
with open(args[1]) as f:
ignoreline = False
content = f.readlines()
content = [x.strip() for x in content]
for value in enumerate(content):
if not(value[1][0] == "!") and ignoreline == False:
firstpart = value[1].split(".")[0]
lenoffirstpart = len(value[1].split(".")[0])
afterpart = str(value[1][lenoffirstpart + 1:])
apwithcomma = afterpart.replace(".", "', '")
preprint = str(firstpart + "(" + apwithcomma + ")")
printtext = preprint.replace("(", "('")
lastprinttext = printtext.replace(")", "')")
try:
exec(str("syntax." + lastprinttext))
except Exception as e:
template = "ERROR: An error of type {0} occured while running line {1} because {2}"
message = template.format(
type(e).__name__, str(value[0] + 1), str(e.args[0]))
print(message)
quit(1)
elif content[value[0]][0] == "!!!":
ignoreline = not(ignoreline)
quit(0)
The syntax.py file looks like this:
def print_message(contents=''):
print(contents)
The test.ros file looks like this:
! This is a single line comment
!!!
This line should be ignored
and this one as well
!!!
print_message.Hello World
The problem appears to be in line 16 of the run-file.py file:
if not(value[1][0] == "!") and ignoreline == False:
I've already tried replacing value[1][0] with (value[1])[0] and other combinations with brackets to no avail.
It seems like when I try to print the value it behaves as expected and gives me ! which is the first character of the test.ros file but for some reason, it throws an exception when it's in the if statement.
If you want any more of the source, it's on Github and you can find the exact commit containing all the files here
Update/Solution
Big thanks to Idanmel and Klaus D. for helping me resolve my issue. You can view the changes I've made here
This happens because the 2nd line in test.ros is empty.
You create content in this example to be:
['! This is a single line comment',
'',
'!!!',
'This line should be ignored',
'and this one as well',
'!!!',
'',
'print_message.Hello World']
When you try to access content[1][0], you get an IndexError because it's an empty string.
Try removing the empty lines from content by adding an if to the list comprehenssion:
content = [x.strip() for x in content if x.strip()]
I'm having some issues with this, I keep getting:
AttributeError: 'int' object has no attribute 'encode'
When I run it.
I thought UTF-8 would be the go to for this. Subscribers will only ever return numbers, or NoneTypes.
Any help would be greatly appreciated.
import urllib2,time,csv,json,requests,urlparse,pdb
SEARCH_URL = urllib2.unquote("http://soyuz.elastic.tubularlabs.net:9200/intelligence_v2/channel_intelligence/%s")
reader = csv.reader(open('input.csv', 'r+U'), delimiter=',', quoting=csv.QUOTE_NONE)
#cookie = {"user": "2|1:0|10:1438908462|4:user|36:eyJhaWQiOiA1Njk3LCAiaWQiOiA2MzQ0fQ==|b5c4b3adbd96e54833bf8656625aedaf715d4905f39373b860c4b4bc98655e9e"}
myfile = open('accounts.csv','w')
writer = csv.writer(myfile, quoting=csv.QUOTE_MINIMAL)
processCount = 1
idsToProcess = []
for row in reader:
if len(row)>0:
idsToProcess.append(row[0])
#idsToProcess = ['fba_491452930867938']
for userID in idsToProcess:
# print "fetching for %s.." % fbid
url = SEARCH_URL % userID
facebooksubscribers = None
Instagramsubscribers = None
vinesubscribers = None
response = requests.request("GET", url)
ret = response.json()
titleResponse = ret['_source']['title']
try:
facebooksubscribers = ret['_source']['facebook']['subscribers']
except:
facebooksubscribers = " "
try:
instagramsubscribers = ret['_source']['instagram']['subscribers']
except:
instagramsubscribers = " "
try:
vinesubscribers = ret['_source']['vine']['subscribers']
except:
vinesubscribers = " "
time.sleep(0)
row = [s.encode('utf-8') for s in [userID,titleResponse,facebooksubscribers,instagramsubscribers,vinesubscribers]]
writer.writerow(row)
#writer.writerow([userID,titleResponse,facebooksubscribers,instagramsubscribers,vinesubscribers,twitterURL])
myfile.flush()
print u"%s,%s,%s,%s,%s,%s" % (processCount,userID,titleResponse,facebooksubscribers,instagramsubscribers,vinesubscribers)
processCount += 1
#print sumEngs
#print vidToEngs
#print sum(vidToEngs.values())
myfile.close()
exit()
Use this :
repr(s).encode('utf-8')
instead of :
s.encode('utf-8')
because one of these
[userID,titleResponse,facebooksubscribers,instagramsubscribers,vinesubscribers]
element is int and you can't perform encode operation on int. You may want to do the type casting in your for loop. Replace
row = [s.encode('utf-8') for s in [userID,titleResponse,facebooksubscribers,instagramsubscribers,vinesubscribers]]
with
row = [str(s).encode('utf-8') for s in [userID,titleResponse,facebooksubscribers,instagramsubscribers,vinesubscribers]]
I had a similar issue when loading data from an xlsx file. The problem I ran into after implementing the solutions above was that I would receive the error:
AttributeError: 'int' object has no attribute 'encode'
since the data I was parsing was not just unicode. The solution I found was a simple try/except where I only .encode('utf-8') if an error gets thrown. Here is the code:
try:
s2 = str(foo)
except:
s2 = foo.encode('utf-8').strip()
I don't know if this was a one off thing or if other people might be having this issue. I hope this helps.
Ive created a simple dns.query function, I am attempting to add the results into a list or potentially a dictionary. However I cant work out how to achieve it, I have tried list.append(subdomain, item), ive tried using the join function and I have tried to use the update function respectably.
Any pointers would be appreciated.
ORIGINAL
def get_brutes(subdomain):
targets = []
try:
myResolver = dns.resolver.Resolver()
myResolver.nameservers = ['8.8.8.8']
myAnswers = myResolver.query(subdomain)
for item in myAnswers.rrset:
targets.append(subdomain,item)
except Exception as e:
pass
return targets
FIX
def get_brutes(subdomain):
targets = []
try:
myResolver = dns.resolver.Resolver()
myResolver.nameservers = ['8.8.8.8']
myAnswers = myResolver.query(subdomain)
for item in myAnswers.rrset:
targets.append(subdomain + ' ' + str(item))
except Exception as e:
pass
return targets
I have recently been practicing my skills at figuring out my own problems but this one problem is persistent. This is the problematic code:
with open('login_names.txt', 'r') as f:
login_name = [line.rstrip('\n') for line in f]
k = input("name: ")
if k in login_name :
print("No errors")
else:
print("You have an error")
else:
print('fail')
#var = login_name.index[random]
check = login_pass[login_name.index[random]]
with open('login_passw.txt', 'r') as p:
login_pass = [line.rstrip('\n') for line in p]
s = input("pass: ")
if s == check :
print("Works")
else:
print("Doesn't work")
f.close()
p.close()
Basically when I run the code it says:
Traceback (most recent call last):
File "C:/Python33/Test.py", line 29, in <module>
check = login_pass[login_name.index[random]]
TypeError: 'builtin_function_or_method' object is not subscriptable
I have tried lots of different suggestions on different questions but none of them have worked for me...
If we assume that login_pass, login_name and random are defined in the namespace that line is in, the only problem you have is that you should write
check = login_pass[login_name.index(random)]
str.index is a function that returns the first index of the argument given in str, so you use () instead of [], which you would use for lists, tuples and dictionaries.