Python Infinite While Loop Not Consistent - python

The code I have wrote in Python for an infinite loop works fine the first time. However, it gives the following message upon the second run:
Traceback (most recent call last):
File "C:/Users/dell/PycharmProjects/pythonProject/main.py", line 27, in
symbol = str(symbol)
TypeError: 'tuple' object is not callable
Any ideas why I am not getting this message after second run?
from xlrd import open_workbook
import win32com.client as win32
from oandapyV20.contrib.requests import MarketOrderRequest
from oandapyV20.contrib.requests import TakeProfitDetails, StopLossDetails
import oandapyV20.endpoints.orders as orders
import oandapyV20
from oandapyV20 import API
import oandapyV20.endpoints.accounts as accounts
import oandapyV20.endpoints.pricing as pricing
import oandapyV20.endpoints.positions as positions
import easygui
import tkinter as tk
import time
while True:
time.sleep(5)
excel = win32.gencache.EnsureDispatch('Excel.Application')
for wb in excel.Workbooks:
if wb.Name == 'forex2.xlsx':
wb.Save()
wb = open_workbook('C:/Users/dell/Documents/forex2.xlsx')
xl_sheet = wb.sheet_by_index(0)
marginrate = xl_sheet.cell(1, 2)
symbol = xl_sheet.cell(1, 1)
symbol = str(symbol)
marginrate = str(marginrate)
symbol = symbol.replace("text:", "")
marginrate = 20
symbol = symbol.replace("'", "")
print("Symbol:", symbol)
print("Margin Rate:", marginrate)
access_token = "XXXX"
accountID = "XXXX"
client = API(access_token=access_token)
r = accounts.AccountDetails(accountID)
client.request(r)
dict = r.response
params = {"instruments": symbol}
r2 = pricing.PricingInfo(accountID=accountID, params=params)
rv2 = client.request(r2)
a = list(rv2.items())[1][1][0]
ask = float(a['closeoutAsk'])
print("Starting Ask:", ask)
a = list(dict.items())[0][1]
marginUsed = float(list(a.items())[25][1])
marginAvailable = float(list(a.items())[26][1])
balance = float(list(a.items())[9][1])
print("Margin Available:", marginAvailable)
print("Balance:", balance)
print("Margin Used + Margin Available:", balance)
STOP_LOSS = .001
TAKE_PROFIT = 100000
units0 = round((marginrate * marginAvailable) / ask * .95)
print("Order Units:", units0)
mktOrder = MarketOrderRequest(
instrument=symbol,
units=units0,
takeProfitOnFill=TakeProfitDetails(price=TAKE_PROFIT).data,
stopLossOnFill=StopLossDetails(price=STOP_LOSS).data)
r = orders.OrderCreate(accountID, data=mktOrder.data)
try:
rv = client.request(r)
except oandapyV20.exceptions.V20Error as err:
print("")
print("UNITS_INVALID")
else:
print("")
excel = win32.gencache.EnsureDispatch('Excel.Application')
for wb in excel.Workbooks:
if wb.Name == 'forex2.xlsx':
wb.Save()
book = open_workbook('C:/Users/dell/Documents/forex2.xlsx')
r = positions.PositionList(accountID=accountID)
client.request(r)
dict = r.response
a = list(dict.items())[0][1]
for i, element in enumerate(a):
long = a[i]
long2 = long['long']
symbol = long['instrument']
try:
averagePrice = long2['averagePrice']
except:
pass
else:
window = tk.Tk()
frame_a = tk.Frame()
label_a = tk.Label(master=frame_a, text="Hello")
label_a.pack()
frame_a.pack()
for sheet in book.sheets():
for rowidx in range(sheet.nrows):
row = sheet.row(rowidx)
for colidx, cell in enumerate(row):
if cell.value == symbol:
row = rowidx + 3
current_bid = sheet.cell(1, row)
current_bid = str(current_bid)
current_bid = float(current_bid.replace("number:", ""))
str = "Beginning Balance:", balance, "Current Bid:", current_bid, "Average Price:", averagePrice, "Current Profit:", round(
(current_bid - float(averagePrice)) * units0, 2)
print(str)
data = {"longUnits": "ALL"}
r = positions.PositionClose(accountID=accountID, instrument=symbol, data=data)
client.request(r)

The problem is your using
str = "Beginning Balance:", balance, "Current Bid:", current_bid, "Average Price:", averagePrice, "Current Profit:", round((current_bid - float(averagePrice)) * units0, 2) ,which replaces the function str with the variable you are assigning here. try replacing the name of this variable and it should work fine.

Related

How can I convert array to Excel from Python?

I'm trying to extract my data into Excel, but I'm having a problem
in this part:
sheet.cell(row=i+2, column=7).value = OeFC1b.value
So I use print() and check the value. It is 50.20042375032.
I get this error message:
raise ValueError("Cannot convert {0!r} to Excel".format(value))
ValueError: Cannot convert array(50.20042375) to Excel
Why is it an array and how do I extract that data?
Here is the whole code:
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 16 18:18:01 2022
#author: mskim
"""
import pandas as pd
import cvxpy as cp
import numpy as np
import openpyxl
Demand_Excel = pd.read_excel('Input/Demands.xlsx',index_col=0)
data = pd.DataFrame(Demand_Excel)
wb = openpyxl.Workbook()
sheet = wb.active
sheet.cell(row=1, column=1).value = "총 수익"
sheet.cell(row=1, column=2).value = "그리드 판매 수익"
sheet.cell(row=1, column=3).value = "연료 가격"
sheet.cell(row=1, column=4).value = "건물 전기 절약값"
sheet.cell(row=1, column=5).value = "난방비 판매값"
sheet.cell(row=1, column=6).value = "전기차 전기 절약값"
sheet.cell(row=1, column=7).value = "수소차 탱크 절약값"
sheet.cell(row=1, column=8).value = "FC1 그리드 판매량"
sheet.cell(row=1, column=9).value = "FC1 건물 사용량"
sheet.cell(row=1, column=10).value = "FC1 전기차 사용량"
sheet.cell(row=1, column=11).value = "FC2 발전량"
sheet.cell(row=1, column=12).value = "CHP 발전량"
sheet.cell(row=1, column=13).value = "PV 그리드 판매량"
sheet.cell(row=1, column=14).value = "PV 건물 사용량"
sheet.cell(row=1, column=15).value = "PV 전기차 사용량"
#sheet.cell(row=1, column=1).value = ""
for i in range(0,2): # Time Regulation (0,8759)
OeFC1g = cp.Variable()
OeFC1b = cp.Variable()
OeFC1e = cp.Variable()
OeFC2 = cp.Variable()
OeCHP = cp.Variable()
OePVg = cp.Variable()
OePVb = cp.Variable()
OePVe = cp.Variable()
BD = np.array(data.iloc[[i],[0]])
EV = np.array(data.iloc[[i],[1]])
HD = np.array(data.iloc[[i],[2]])
PFC1 = 9.33863636
PFC2 = 12.94857
PCHP = 14.22143
hFC1 = 0.50818182
hFC2 = 0.393143
hCHP = 2.297429
HFC2 = 0.025714
PGAS = 19.3870
PP = np.array(data.iloc[[i],[3]])
heat=396.76
Hprice=8000
constraints = [
0<=OeFC1g,
OeFC1g<=440,
0<=OeFC1b,
OeFC1b<=440,
0<=OeFC1e,
OeFC1e<=440,
OeFC1g + OeFC1b + OeFC1e <= 440,
0<=OePVg,
OePVg<=50,
0<=OePVb,
OePVb<=50,
0<=OePVe,
OePVe<=50,
OePVg + OePVb + OePVe == 50,
0<=OeFC2,
OeFC2<=350,
0<=OeCHP,
OeCHP<=140,
OeFC1b + OePVb == BD,
OeFC1e + OePVe == EV
]
# Korean Money Unit Won
heat_profit = ((OeFC1e + OeFC1g + OeFC1b) * hFC1 + OeFC2 * hFC2 +OeCHP * hCHP) * heat
Power_sell = PP * (OeFC2 + OeCHP + OeFC1g + OePVg )
Fuel_Price = ((OeFC1e + OeFC1g + OeFC1b) * PFC1 + OeFC2 * PFC2 +OeCHP * PCHP) * PGAS
Building_profit = BD * 100 + 6160 # 100 is buying price for electric power, other is base price
EV_profit = EV*100 + 2390 # 100 is buying price for electric power, other is base price
H2_profit = Hprice * ( OeFC2 * HFC2 - HD) # We have H2 tanks
obj = cp.Maximize( Power_sell - Fuel_Price + EV_profit + H2_profit + Building_profit + heat_profit )
prob = cp.Problem(obj, constraints)
prob.solve()
sheet = wb.active
print(OeFC1b.value)
sheet.cell(row=i+2, column=1).value = obj.value
sheet.cell(row=i+2, column=2).value = Power_sell[0][0].value
sheet.cell(row=i+2, column=3).value = Fuel_Price.value
sheet.cell(row=i+2, column=4).value = Building_profit[0][0]
sheet.cell(row=i+2, column=5).value = heat_profit.value
sheet.cell(row=i+2, column=6).value = EV_profit[0][0]
sheet.cell(row=i+2, column=7).value = H2_profit[0][0].value
sheet.cell(row=i+2, column=7).value = OeFC1b.value #error
# sheet.cell(row=i+2, column=10).value = OeFC2.value
wb.save('Output/test_for_excel.xlsx')
Im not familiar with the cvxpy lib but i belive you are trying to write a list to the excel document. I don't think that is supported.
This code produce a similar error
import openpyxl
val = [50.20042375]
wb = openpyxl.Workbook()
sheet = wb.active
sheet.cell(row=1, column=1).value = val
To fix the issue do add a [0] in the end like this
import openpyxl
val = [50.20042375]
wb = openpyxl.Workbook()
sheet = wb.active
sheet.cell(row=1, column=1).value = val[0]

why it say "the action cannot be completed because the file is open in python“?

def main_loop():
global errname, errtime, error_detail, conclusion
error_detail = ""
facts_all = {}
facts = []
buffer = 0
current_time = datetime.now()
while os.path.exists("C:\Winusr"):
print(paths["wintrace"])
try:
start_point = 0
old_size = os.path.getsize(paths["wintrace"])
while os.path.getsize(paths["wintrace"])>= old_size:
#fo = open(paths["wintrace"], "rb")
#fo.seek(start_point,1)
shutil.copyfile(paths["wintrace"], "C:\Winusr\wintrace1.log")
fo = open("C:\Winusr\wintrace1.log", "rb")
fo.seek(start_point, 1)
errtime = datetime(1900, 1, 1)
old_size = os.path.getsize(paths["wintrace"])
#start from here
for line in fo.readlines():
line = str(line.decode('ISO-8859-1'))
print(line)
if fnmatch.fnmatch(line, "*START DUMP LOG BUFFER*"):
buffer = 1
if fnmatch.fnmatch(line, "*END DUMP LOG BUFFER*"):
buffer = 0
if buffer == 1:
continue
facts_all = collect_facts(line,facts_all,key_string,key_value_dic)
for pattern in error_detect:
if fnmatch.fnmatch(line, pattern):
try:
err_type = df[df["Error Detect Keyword"] == pattern]["Err Type"].to_string(index=False).lstrip()
errname = df[df["Err Type"] == err_type]["Error Name"].tolist()[0].lstrip()
errtime = datetime.strptime(
datetime.fromtimestamp(os.path.getmtime(paths["wintrace"])).strftime("%Y-%m-%d") + " " + line[:8], "%Y-%m-%d %H:%M:%S") #"%d-%b-%Y %H:%M:%S"
#errtime = datetime.fromtimestamp(os.path.getmtime(paths["wintrace"])).strftime("%Y-%m-%d") + " " + line[:8]
#errtime = errtime.strftime('%Y-%m-%d %H:%M:%S')
product = re.findall(r"[/](.+?)[.]", paths["cur"])
product = product[0].split("/")[-1]
tester = tester_name(paths["cur"])
if len(facts_all) != 0:
facts.append(errname)
#idex = 9999
for fact, line in facts_all.items():
if fact in dic1[errname]:
error_detail = error_detail + line + '\n'
facts.append(fact)
print("err_detail1", error_detail)
if len(facts) != 1:
facts = list(set(facts))
conclusion = inference_engine(facts)
print("errtime", errtime)
print("current_time", current_time)
if conclusion != "cannot find solution for this error" and errtime > current_time:
solutions = sop2(errlist, errname, conclusion)
row = recording(tester, product, errname, errtime, error_detail, conclusion)
print("gg pop out GUI!!!")
#send_email(errname, errtime, tester, error_detail)
GUI(errname, errtime, error_detail, conclusion, solutions, row)
current_time = datetime.now()
workbook = xlrd.open_workbook(r"G:\expert system data\Machine Database.xls")
workbook1 = copy(workbook)
ws1 = workbook1.get_sheet(0)
style = xlwt.XFStyle()
style.num_format_str = 'yyyy-mm-dd hh:mm:ss'
ws1.write(row, 8, current_time, style)
workbook1.save(r"G:\expert system data\Machine Database.xls")
error_detail = ""
facts_all = {}
facts = []
error_detail = ""
facts_all = {}
facts = []
except:
continue
start_point = fo.tell()
fo.close()
except:
continue
else:
main_loop()
the paths["wintrace"] is ""C:\Winusr\Wintrace.log", i dont want it is open cause sometimes need to change its name or delete, i copy this file and open the copied one, but it still show it is open, can u help me check where it is opened? besides, i use "filepath = tkinter.filedialog.askopenfilename()", but dont think it will open the wintrace file.the error screenshot

exception used to pop up alert box from button event in tkinter, cant find out the root for the problem

so my program takes a directory with excel files with one line and combine them all into one.
The gui has two buttons one to choose the path and one to save the wanted path.
I created a gui class and im basically trying to pass the OptionMenu chosen text forward after an event was made, but an exception is raised and Im struggling with,
long story short:
import os
from tkinter import *
from tkinter import filedialog
from CombineExcelFiles import *
class GUI:
def __init__(self, master):
self.master = master
master.title('מיזוג קבצי אקסל')
master.geometry('220x100')
self.credit = Label(master, text='')
self.credit.pack()
self.variable = StringVar(master)
self.variable.set('חלבי')
self.opt = OptionMenu(master, self.variable, 'חלבי', 'פרווה')
self.opt.pack()
Button(window, text='בחר תיקייה למיזוג', command=upload).pack(side=RIGHT)
Button(window, text='בחר תייקת הורדה', command=save).pack(side=LEFT)
def upload():
global basepath
basepath = filedialog.askdirectory()
def save():
#print(self.variable.get())
try: #This is line 25
basepath
file_list = []
download_path = filedialog.askdirectory()
for entry in os.listdir(basepath):
if os.path.isfile(os.path.join(basepath, entry)):
if entry[len(entry)-5:] == '.xlsx' and len(entry) == 17:
file_list.append(entry)
data = getData(basepath, file_list)
writeToFile(data, file_list, download_path, master.variable.get())
except NameError:
tkinter.messagebox.showerror('ERROR', 'בחר תיקיית מקור')
This is the writeToFile from CombineExcelFiles:
def writeToFile(data, files,download_path,variable):
file = Workbook()
ws = file.active
center = Alignment(horizontal='center', vertical='center')
br = Border(left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin'))
.
.
.
col = 'C'
row = 3
count = 0
for i in data:
temp = files[count]
for j in i[::-1]:
if type(j) == int or type(j) == float:
ws[col + str(row)].value = ('%.2f' %j)
ws[col + str(row)].alignment = center
ws[col + str(row)].border = br
col = chr(ord(col)+1)
ws['J' + str(row)].value = temp[6:8] + '/' + temp[4:6] + '/' + temp[:4]
ws['K' + str(row)].value = temp[8:10] + ':' + temp[10:12]
row +=1
col = 'C'
ws = fitToCell(ws)
temp_date = datetime.now()
file.save(download_path + '/' + 'מעקב ' + variable + str(temp_date.month) + '-' +
str(temp_date.year) + '.xlsx' )
The error that was given is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\******\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:/Users/******/CombineExcels/mainProject.py", line 25, in save
print(self.variable.get())
TypeError: writeToFile() missing 1 required positional argument: 'variable'
Thank you in advance
Edit, Ive put the code n one file so it will be runnable:
import os
from tkinter import *
from tkinter import filedialog
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.styles import Alignment
from openpyxl.styles.borders import Border, Side
from datetime import datetime
class GUI:
def __init__(self, master):
self.master = master
master.title('מיזוג קבצי אקסל')
master.geometry('220x100')
self.credit = Label(master, text='')
self.credit.pack()
self.variable = StringVar(master)
self.variable.set('בחר מרשימה')
self.opt = OptionMenu(master, self.variable, 'חלבי', 'פרווה')
self.opt.pack()
Button(window, text='בחר תיקייה למיזוג', command=upload).pack(side=RIGHT)
Button(window, text='בחר תייקת הורדה', command=save).pack(side=LEFT)
#START GUI PROPERTIES
def upload(self):
global basepath
basepath = filedialog.askdirectory()
print(master)
def save(self):
file_list = []
download_path = filedialog.askdirectory()
for entry in os.listdir(basepath):
if os.path.isfile(os.path.join(basepath, entry)):
if entry[len(entry)-5:] == '.xlsx' and len(entry) == 17:
file_list.append(entry)
data = getData(basepath, file_list)
print(self.variable.get())
writeToFile(data, file_list, download_path)
#STOP GUI PROPERTIES
def getData(self, basepath, file_list):
a = []
for file in file_list:
load_workbook(basepath + '/' + file)
tempData = []
for cell in temp['Sheet1']:
for value in cell:
if value.value == None:
continue
else:
tempData.append(value.value)
data.append(tempData)
return data
def fitToCell(self, ws): #get used columns and than fit cell's width into length of letters
dict = {}
for cell in ws:
for value in cell:
temp = str(value.value)
if temp:
if value.coordinate[0] not in dict:
dict[value.coordinate[0]] = len(temp)
elif len(temp) > dict[value.coordinate[0]]:
dict[value.coordinate[0]] = len(temp)
for col in dict:
ws.column_dimensions[col].width = dict[col]
return ws
def writeToFile(self, data, files,download_path):
file = Workbook()
ws = file.active
center = Alignment(horizontal='center', vertical='center')
br = Border(left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin'))
print(ws.evenHeader.right.text)
if self.variable.get() == 'חלבי':
ws['C2'].value = 'חלב רצוי'
ws['C2'].alignment = center
ws['C2'].border = br
ws['D2'].value = 'חלב מצוי'
ws['D2'].alignment = center
ws['D2'].border = br
ws['E2'].value = 'קקאו רצוי'
ws['E2'].alignment = center
ws['E2'].border = br
ws['F2'].value = 'קקאו מצוי'
ws['F2'].alignment = center
ws['F2'].border = br
ws['G2'].value = 'שמן רצוי'
ws['G2'].alignment = center
ws['G2'].border = br
ws['H2'].value = 'שמן מצוי'
ws['H2'].alignment = center
ws['H2'].border = br
ws['I2'].value = 'סוכר רצוי'
ws['I2'].alignment = center
ws['I2'].border = br
ws['J2'].value = 'סוכר מצוי'
ws['J2'].alignment = center
ws['J2'].border = br
ws['I2'].value = 'מספר מתכון'
ws['I2'].alignment = center
ws['I2'].border = br
ws['J2'].value = 'זמן ייצור'
ws['J2'].alignment = center
ws['J2'].border = br
ws['K2'].value = 'תאריך ייצור'
ws['K2'].alignment = center
ws['K2'].border = br
col = 'C'
row = 3
count = 0
for i in data:
temp = files[count]
for j in i[::-1]:
if type(j) == int or type(j) == float:
ws[col + str(row)].value = ('%.2f' %j)
ws[col + str(row)].alignment = center
ws[col + str(row)].border = br
col = chr(ord(col)+1)
ws['J' + str(row)].value = temp[6:8] + '/' + temp[4:6] + '/' + temp[:4]
ws['J' + str(row)].alignment = center
ws['J' + str(row)].border = br
ws['K' + str(row)].value = temp[8:10] + ':' + temp[10:12]
ws['K' + str(row)].border = br
ws['K' + str(row)].alignment = center
row +=1
col = 'C'
ws = fitToCell(ws)
temp_date = datetime.now()
file.save(download_path + '/' + 'מעקב ' + self.variable.get() +' ' + str(temp_date.month) + '-' + str(temp_date.year) + '.xlsx' )
window = Tk()
my_gui = GUI(window)
#print(my_gui.variable.get())
window.mainloop()
This is the error:
runfile('C:/Users/*****/Desktop/תכנות/untitled2.py',
wdir='C:/Users/*****/Desktop/תכנות')
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\*****\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:/Users/*****/CombineExcels/mainProject.py", line 25, in save
TypeError: writeToFile() missing 1 required positional argument: 'var'
For some reason it keeps returning from another path
solved it, had put all the methods inside the object, while the events func inside the init.
also i ran too many times the program so the errors were not related to my code...

'Int' object has no attribute

I am trying to create a list objects that holds data about professional golfers. The different data points are golfer name and putting percentages from different distances. I want to sort this list of objects by name once all the data has been entered for every player object. The list of these objects is called PlayerNumber. When I try to sort PlayerNumber by attribute 'name'. I get an error stating that 'int' has no attribute and I am not sure why PlayerNumber is being referred to as an integer and not a list.
Any help would be appreciated. Here is the code:
import operator
import numpy as np
import statistics
import matplotlib.pyplot as plt
from colour import Color
from bs4 import BeautifulSoup
import urllib3
############### ACCESS WEBPAGES ####################
def makeSoup(url):
http = urllib3.PoolManager()
response = http.request('GET', url)
soupdata = BeautifulSoup(response.data)
return soupdata
siteURL = []
for i in range(7):
siteURL.append(i)
siteURL[0] = ''
siteURL[1] = 'http://www.pgatour.com/stats/stat.408.html' #>25
siteURL[2] = 'http://www.pgatour.com/stats/stat.407.html' #20-25
siteURL[3] = 'http://www.pgatour.com/stats/stat.406.html' #15-20
siteURL[4] = 'http://www.pgatour.com/stats/stat.405.html' #10-15
siteURL[5] = 'http://www.pgatour.com/stats/stat.404.html' #5-10
siteURL[6] = 'http://www.pgatour.com/stats/stat.02427.html' #3-5
############### ACCESS TABLE DATA ###################
def row_number(soupdata):
for row in table.findAll('tr'):
tot_row = row
return tot_row
def parse_table(soupdata):
currRank = []
prevRank = []
playerName = []
rounds = []
pctMake = []
attempts = []
puttsMade = []
table = soupdata.find('tbody')
tot_row = 0
for row in table.findAll('tr'):
#for col in row.findAll('td'):
col = row.find_all('td')
#column_1 = col[0]
#currRank.append(column_1)
#column_2 = col[1]
#prevRank.append(column_2)
column_3 = col[2].text
column_3.strip()
playerName.append(column_3)
#column_4 = col[3]
#rounds.append(column_4)
column_5 = col[4].text
pctMake.append(column_5)
#column_6 = col[5]
#attempts.append(column_6)
#column_7 = col[6]
#puttsMade.append(column_7)
tot_row += 1
#return currRank, prevRank, playerName, rounds, pctMake, attempts, puttsMade
return playerName, pctMake, tot_row
"""
>25 ft: distance1
20-25 ft: distance2
15-20 ft: distance3
10-15 ft: distance4
5-10 ft: distance5
3-5 ft: distance6
"""
############### CLASS DEFINITION ###################
class Player:
id_list={}
def __init__(self,name, id, dis1=0.0, dis2=0.0, dis3=0.0, dis4=0.0, dis5=0.0, dis6=0.0):
self.name = name
self.dis1 = dis1
self.dis2 = dis2
self.dis3 = dis3
self.dis4 = dis4
self.dis5 = dis5
self.dis6 = dis6
self.id = id
Player.id_list[self.name] = self # save the id as key and self as he value
def addDis1(self,distance1):
self.dis1 = float(distance1)
def addDis2(self,distance2):
self.dis2 = float(distance2)
def addDis3(self,distance3):
self.dis3 = float(distance3)
def addDis4(self,distance4):
self.dis4 = float(distance4)
def addDis5(self,distance5):
self.dis5 = float(distance5)
def addDis6(self,distance6):
self.dis6 = float(distance6)
def displayPlayer(self):
print("Player: ", self.name, '\n'
">25 Ft %: ", self.dis1, '\n'
"20-25 Ft %: ", self.dis2, '\n'
"15-20 Ft %: ", self.dis3, '\n'
"10-15 Ft %: ", self.dis4, '\n'
"5-10 Ft %: ", self.dis5, '\n'
"3-5 Ft %: ", self.dis6, '\n')
#classmethod
def lookup_player_name_by_id(cls, name):
try:
return cls.id_list[name] # return the instance with the id
except KeyError: # error check for if id does not exist
raise KeyError("No user with id %s" % str(id))
############### DATA POPULATION ###################
PlayerNumber=[]
for i in range(0,195):
PlayerNumber.append(i)
for i in range(1,7):
soupdata = makeSoup(siteURL[i])
playerName, pctMake, tot_row = parse_table(soupdata)
for x in range(0,tot_row):
#PlayerNumber.append(x)
name = playerName[x]
name = name.replace("\xa0", " ")
name = name.replace("\n", "")
if i == 1:
PlayerNumber[x] = Player(name, x)
Player.addDis1(PlayerNumber[x],pctMake[x])
if i == 2:
val = Player.lookup_player_name_by_id(name)
Player.addDis2(PlayerNumber[val.id],pctMake[x])
if i == 3:
val = Player.lookup_player_name_by_id(name)
Player.addDis3(PlayerNumber[val.id],pctMake[x])
if i == 4:
val = Player.lookup_player_name_by_id(name)
Player.addDis4(PlayerNumber[val.id],pctMake[x])
if i == 5:
val = Player.lookup_player_name_by_id(name)
Player.addDis5(PlayerNumber[val.id],pctMake[x])
if i == 6:
val = Player.lookup_player_name_by_id(name)
Player.addDis6(PlayerNumber[val.id],pctMake[x])
PlayerNumber.sort(key = operator.attrgetter("name"))
#PlayerNumber[2].displayPlayer()
I'm using Python 3.4 spyder IDE. I'm relatively new to python as an FYI.
Thanks!
It isn't that PlayerNumber is being referred to as an integer, but rather that PlayerNumber is a list of integers, and every element of that list (and integer) doesn't has an attribute "name", which sort() is trying to access (in order to sort them).
Edit:
To elaborate, the second to last line in your sample:
PlayerNumber.sort(key = operator.attrgetter("name"))
is trying to sort PlayerNumber, using the comparison function: operator.attrgetter("name"), which means it must call that function on each element of PlayerNumber to get its rank in the sorted array. That is why you are trying to grab a .name attribute from the integers in PlayerNumber.

Get data into sqlite from yahoo finance

I trying to get yahoo prices into sqlite...
I have the code below, but cant get the data into ipull []
then into sqlite...
from urllib import urlopen
import win32com.client as win32
import sqlite3
RANGE = range(3, 8)
COLS = ('TICKER', 'PRICE', 'Vol')
URL = 'http://quote.yahoo.com/d/quotes.csv?s=%s&f=sl1v'
TICKS = ('GGP', 'JPM', 'AIG', 'AMZN')
ipull =[]
def excel():
app = 'Excel'
xl = win32.gencache.EnsureDispatch('%s.Application' % app)
ss = xl.Workbooks.Add()
sh = ss.ActiveSheet
xl.Visible = True
for x in range(3):
sh.Cells(5, x+1).Value = COLS[x]
row = 6
u = urlopen(URL % ','.join(TICKS))
for data in u:
tick, price, per = data.split(',')
sh.Cells(row, 1).Value = eval(tick)
sh.Cells(row, 2).Value = ('%.2f' % float(price))
sh.Cells(row, 3).Value = eval(per.rstrip())
row += 1
u.close()
con = sqlite3.connect('/py/data/db2')
c = con.cursor()
c.execute('INSERT INTO prices VALUES (?,?,?)', ipull)
con.commit()
c.close()
if __name__=='__main__':
excel()
You declare ipull[], but never assign it.

Categories

Resources