Python elif: syntax error - python-2.7

Hi guys I have a syntax error that I really don't understand... Anyone can help?
I get this message on the console:
File "./data_4.0.1.py", line 170
elif:
^
SyntaxError: invalid syntax
The error is raised on this elif:
#controllo ultimo timestamp
elif:
with open(nomen, 'rb') as f:
last_timestamp = f.readlines()[-1].split(",")[0]
Here is my code:
def funzione_aggiornamento_prezzi(titolo,timeframe,lookback):
#parametri per scaricare lo storico dei prezzi
if timeframe =='TBT':
lookback = 0
elif timeframe =='1M':
lookback = 7
elif timeframe =='5M':
lookback = 60
elif timeframe =='60M':
lookback = 180
elif timeframe =='1D':
lookback = 1800
params = {'item': titolo,
'frequency': timeframe,
'dataDa':x_giorni_fa(lookback)}
try:
r = requests.get(myurl, params=params)
except:
pprint("Si e' verificato un errore")
else:
pprint(r.status_code)
pprint(r.url)
new_list = crea_lista(r)
#codice per scrivere su di un csv da una lista
nomen = "%s.%s.csv" % (titolo,timeframe)
csvfile = open(nomen, 'a')
reportwriter = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL)
#codice per scrivere su di un csv
#controllo del numero di rows nel file
with open(nomen,"r") as f:
reader = csv.reader(f,delimiter = ",")
data = list(reader)
row_count = len(data)
if row_count == 0:
for i in new_list:
da_appendere = i
reportwriter.writerow(da_appendere)
csvfile.close()
#controllo ultimo timestamp
elif:
with open(nomen, 'rb') as f:
last_timestamp = f.readlines()[-1].split(",")[0]
#codice per appendere solo i nuovi dati
found_it = 0
for i in range((len(new_list))-1):
if new_list[i] == last_timestamp:
found_it = 1
if found_it == 1:
this_elem = new_list[i]
next_elem = new_list[(i+1)]
#print(this_elem)
#print(next_elem)
da_appendere1 = next_elem
reportwriter.writerow(da_appendere1)
csvfile.close()
for i in lista_indici:
for j in lista_timeframe:
funzione_aggiornamento_prezzi(i,j,lookback)

you end the if block in the previous line when put a instruction at the same level indentation that the if statement
if condition:
stuff
something # doing this close the if block
and a elif can only happen in a if block
and you do that in
if row_count == 0:
for i in new_list:
da_appendere = i
reportwriter.writerow(da_appendere)
csvfile.close() #<-- here you close the if block
#controllo ultimo timestamp
elif: #<-- you forgot the condition, and is outside of a 'if' block
with open(nomen, 'rb') as f:
last_timestamp = f.readlines()[-1].split(",")[0]
futhermore you forget to put a condition in the elif, if you don't need one use else instead

If you do not have another if statement, you should use else instead of elif.
See the documentation regarding control-flow.

Related

Redis session does not store variables when modified in thread - Flask

I have a thread that is running inside a route where the thread job is to do some expensive work, store variables and than I'll need to use these variables in another flask route.
When I am using the session variable (Redis) as a parameter in the thread function in order to add the data and extract it later it does not find the variables that I have stored in it.
In contrast, when I declare a global_dict and pass it to the thread function instead of session, the code works great.
As the thread function can be used by multiple users simultaneously, storing it in a global_dict is not a good practice.
Why using session in my code does not work?
In the following code, if I replace global_dict with session I won't be able to access it in the /result route.
Per doc:
"Redis can handle up to 2^32 keys, and was tested in practice to handle at least 250 million keys per instance.
Every hash, list, set, and sorted set, can hold 2^32 elements.
In other words your limit is likely the available memory in your system."
P.S Sorry for the long code blocks.
#app.route("/build",methods=["GET", "POST"])
#login_required
def build():
if request.method == "POST":
global th
global finished
finished= False
#copy_current_request_context
def operation(global_dict):
global finished
symbols = request.form.get("symbols")
mc.set("symbols", symbols)
if contains_multiple_words(symbols) == False:
flash("The app purpose is to optimize a portfolio given a list of stocks. Please enter a list of stocks seperated by a new row.")
return redirect("/build")
Build(session["user_id"], symbols.upper(), request.form.get("start"), request.form.get("end"), request.form.get("funds"), request.form.get("short"), request.form.get("volatility"), request.form.get("gamma"), request.form.get("return"))
db.session.commit()
try:
df = yf.download(symbols, start=request.form.get("start"), end=request.form.get("end"), auto_adjust = False, prepost = False, threads = True, proxy = None)["Adj Close"].dropna(axis=1, how='all')
failed=(list(shared._ERRORS.keys()))
df = df.replace(0, np.nan)
try:
global_dict['listofna']=df.columns[df.isna().iloc[-2]].tolist()+failed
except IndexError:
flash("Please enter valid stocks from Yahoo Finance.")
return redirect("/build")
df = df.loc[:,df.iloc[-2,:].notna()]
except ValueError:
flash("Please enter a valid symbols (taken from Yahoo Finance)")
return redirect("/build")
def enter_sql_data(app, df, nasdaq_exchange_info, Stocks):
for ticker in df.columns:
ticker=ticker.upper()
if any(sublist[1]==ticker in sublist for sublist in nasdaq_exchange_info) is False:
ticker_ln = yf.Ticker(ticker).stats()["price"].get('longName')
if not ticker_ln:
ticker_ln = ticker
ticker_list=[ticker_ln, ticker]
with app.app_context():
new_stock=Stocks(ticker, ticker_ln)
db.session.add(new_stock)
db.session.commit()
nasdaq_exchange_info.extend([ticker_list])
global nasdaq_exchange_info
app1 = app._get_current_object()
p1 = Process(target=enter_sql_data, args=[app1, df, nasdaq_exchange_info, Stocks])
p1.start()
prices = df.copy()
fig = px.line(prices, x=prices.index, y=prices.columns, title='Price Graph')
fig = fig.update_xaxes(rangeslider_visible=True)
fig.update_layout(width=1350, height=900)
global_dict['plot_json'] = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
exp_cov = risk_models.exp_cov(prices, frequency=252)
#plotting the covariance matrix
heat = go.Heatmap(
z = risk_models.cov_to_corr(exp_cov),
x = exp_cov.columns.values,
y = exp_cov.columns.values,
zmin = 0, # Sets the lower bound of the color domain
zmax = 1,
xgap = 1, # Sets the horizontal gap (in pixels) between bricks
ygap = 1,
colorscale = 'RdBu'
)
title = 'Covariance matrix'
layout = go.Layout(
title_text=title,
title_x=0.5,
width=800,
height=800,
xaxis_showgrid=False,
yaxis_showgrid=False,
yaxis_autorange='reversed'
)
fig1=go.Figure(data=[heat], layout=layout)
fig1.update_layout(width=500, height=500)
global_dict['plot_json1'] = json.dumps(fig1, cls=plotly.utils.PlotlyJSONEncoder)
S = risk_models.CovarianceShrinkage(prices).ledoit_wolf()
heat = go.Heatmap(
z = risk_models.cov_to_corr(S),
x = S.columns.values,
y = S.columns.values,
zmin = 0, # Sets the lower bound of the color domain
zmax = 1,
xgap = 1, # Sets the horizontal gap (in pixels) between bricks
ygap = 1,
colorscale = 'RdBu'
)
title = 'Ledoit-Wolf shrinkage'
layout = go.Layout(
title_text=title,
title_x=0.5,
width=800,
height=800,
xaxis_showgrid=False,
yaxis_showgrid=False,
yaxis_autorange='reversed'
)
fig2=go.Figure(data=[heat], layout=layout)
fig2.update_layout(width=500, height=500)
global_dict['plot_json2'] = json.dumps(fig2, cls=plotly.utils.PlotlyJSONEncoder)
#Section 2 -Return estimation
#it is often a bad idea to provide returns using a simple estimate like the mean of past returns. Research suggests that better off not providing expected returns – you can then just find the min_volatility() portfolio or use HRP.
mu = pypfopt.expected_returns.capm_return(prices)
fig3 = px.bar(mu, orientation='h')
fig3.update_layout(width=700, height=500)
global_dict['plot_json3'] = json.dumps(fig3, cls=plotly.utils.PlotlyJSONEncoder)
#using risk models optimized for the Efficient frontier to reduce to min volitility, good for crypto currencies - not implemented in the website now.
ef = EfficientFrontier(None, S)
try:
ef.min_volatility()
weights = ef.clean_weights()
nu = pd.Series(weights)
fig4 = px.bar(nu, orientation='h')
fig4.update_layout(width=700, height=500)
global_dict['plot_json4'] = json.dumps(fig4, cls=plotly.utils.PlotlyJSONEncoder)
av=ef.portfolio_performance()[1]
global_dict['av']=round(av, 3)*1
#if we want to buy the portfolio mentioned above
df = df.iloc[[-1]]
for col in df.columns:
if col.endswith(".L"):
df.loc[:,col] = df.loc[:,col]*GBPtoUSD()
try:
latest_prices = df.iloc[-1]
except IndexError:
flash("There is an issue with Yahoo API please try again later")
return redirect("/")
# prices as of the day you are allocating
if float(request.form.get("funds")) <= 0 or float(request.form.get("funds")) == " ":
flash("Amount need to be a positive number")
return redirect("/build")
if float(request.form.get("funds")) < float(latest_prices.min()):
flash("Amount is not high enough to cover the lowest priced stock")
return redirect("/build")
try:
da = DiscreteAllocation(weights, latest_prices, total_portfolio_value=float(request.form.get("funds")))
except TypeError:
delisted=df.columns[df.isna().any()].tolist()
delisted= ", ".join(delisted)
flash("Can't get latest prices for the following stock/s, please remove to contiue : %s" % delisted)
return redirect("/build")
alloc, global_dict['leftover'] = da.lp_portfolio()
global_dict['alloc']=alloc
global_dict['latest_prices']=latest_prices
except ValueError:
pass
#Maximise return for a given risk, with L2 regularisation
try:
ef = EfficientFrontier(mu, S)
ef.add_objective(objective_functions.L2_reg, gamma=(float(request.form.get("gamma")))) # gamme is the tuning parameter
ef.efficient_risk(int(request.form.get("volatility"))/100)
weights = ef.clean_weights()
su = pd.DataFrame([weights])
fig5 = px.pie(su, values=weights.values(), names=su.columns)
fig5.update_traces(textposition='inside')
fig5.update_layout(width=500, height=500, uniformtext_minsize=12, uniformtext_mode='hide')
global_dict['plot_json5'] = json.dumps(fig5, cls=plotly.utils.PlotlyJSONEncoder)
global_dict['perf'] =ef.portfolio_performance()
except Exception as e:
flash(str(e))
return redirect("/build")
#if we want to buy the portfolio mentioned above
for col in df.columns:
if col.endswith(".L"):
df.loc[:,col] = df.loc[:,col]*GBPtoUSD()
latest_prices1 = df.iloc[-1] # prices as of the day you are allocating
if float(request.form.get("funds")) <= 0 or float(request.form.get("funds")) == " ":
flash("Amount need to be a positive number")
return redirect("/build")
if float(request.form.get("funds")) < float(latest_prices.min()):
flash("Amount is not high enough to cover the lowest priced stock")
return redirect("/build")
da = DiscreteAllocation(weights, latest_prices, total_portfolio_value=float(request.form.get("funds")))
alloc1, global_dict['leftover1'] = da.lp_portfolio()
global_dict['alloc1']=alloc1
global_dict['latest_prices1']=latest_prices1
#Efficient semi-variance optimization
returns = pypfopt.expected_returns.returns_from_prices(prices)
returns = returns.dropna()
es = EfficientSemivariance(mu, returns)
try:
es.efficient_return(float(request.form.get("return"))/100)
except ValueError as e:
flash(str(e))
return redirect("/build")
global_dict['perf2']=es.portfolio_performance()
weights = es.clean_weights()
#if we want to buy the portfolio mentioned above
for col in df.columns:
if col.endswith(".L"):
df.loc[:,col] = df.loc[:,col]*GBPtoUSD()
latest_prices2 = df.iloc[-1] # prices as of the day you are allocating
if float(request.form.get("funds")) <= 0 or float(request.form.get("funds")) == " ":
flash("Amount need to be a positive number")
return redirect("/build")
if float(request.form.get("funds")) < float(latest_prices.min()):
flash("Amount is not high enough to cover the lowest priced stock")
return redirect("/build")
da = DiscreteAllocation(weights, latest_prices, total_portfolio_value=float(request.form.get("funds")))
alloc2, global_dict['leftover2'] = da.lp_portfolio()
global_dict['alloc2']=alloc2
global_dict['latest_prices2']=latest_prices2
mc.delete("symbols")
global_dict['ret']=float(request.form.get("return"))
global_dict['gamma']=request.form.get("gamma")
global_dict['volatility']=request.form.get("volatility")
finished = True
global global_dict
th = Thread(target=operation, args=[global_dict])
th.start()
return render_template("loading.html")
else:
if mc.get("symbols"):
cached_symbols=mc.get("symbols")
else:
cached_symbols=''
availableCash=db.session.query(Users.cash).filter_by(id=session["user_id"]).first().cash
return render_template("build.html", availableCash=round(availableCash, 4), GBP=GBPtoUSD(), nasdaq_exchange_info=nasdaq_exchange_info, cached_symbols=cached_symbols, top_50_crypto=top_50_crypto, top_world_stocks=top_world_stocks, top_US_stocks=top_US_stocks, top_div=top_div)
app.route('/result')
def result():
return render_template("built.html",av=global_dict['av'], leftover=global_dict['leftover'], alloc=global_dict['alloc'], ret=global_dict['ret'],gamma=global_dict['gamma'],volatility=global_dict['volatility'],perf=global_dict['perf'], perf2=global_dict['perf2'], alloc1=global_dict['alloc1'], alloc2=global_dict['alloc2'], plot_json=global_dict['plot_json'], plot_json1=global_dict['plot_json1'], plot_json2=global_dict['plot_json2'], plot_json3=global_dict['plot_json3'], plot_json4=global_dict['plot_json4'], plot_json5=global_dict['plot_json5'], leftover1=global_dict['leftover1'], leftover2=global_dict['leftover2'],listofna=(', '.join(global_dict['listofna'])))

PYTHON: Searching two files for common lines and collecting their contents into set

I have a task to compare two comma separated files. If the first two columns exist in both files, then I have to collect the remaining columns into set from both the files in my results.
If I have the following two files:
a.txt
1,2,3,4
2,4,7,5
3,8,6,7
4,9,5,6
3,8,7,2
b.txt
1,2,4,6
2,3,6,5
3,8,9,2
4,9,6,9
3,5,2,3
6,2,7,3
I want to get the results:
1,2(3,4,4,6)
3,8(6,7,7,2,9,2)
4,9(5,6,6,9)
Is there a more efficient way to implement it? especially as the files maybe large and not fit in the available memory of my computer.
The following is my implement.
KEYNOTFOUND = '<KEYNOTFOUND>'
class dict_cls(object):
#staticmethod
def dict_diff(first, second):
diff = {}
for key in first.keys():
if (not second.has_key(key)):
diff[key] = (first[key], KEYNOTFOUND)
elif (first[key] != second[key]):
diff[key] = (first[key], second[key])
for key in second.keys():
if (not first.has_key(key)):
diff[key] = (KEYNOTFOUND, second[key])
return diff
if __name__ == '__main__':
dict1 = {(1,2):(3,4),(2,4):(7,5),(3,8):(6,7),(4,9):(5,6),(3,8):(7,2)}
dict2 = {(1,2):(4,6),(2,3):(6,5),(3,8):(9,2),(4,9):(6,9),(3,5):(2,3),(6,2):(7,3)}
print dict_cls.dict_diff(dict1, dict2)
import datetime
class FindCommKey(object):
def __init__(self):
self.combine = {}
self.counter = {}
self.result = {}
def find_common_key(self, target_file):
with open(target_file, 'r+') as file_handler:
for line in file_handler:
print(line, end='')
__line = list(map(int, line.strip().split(',')))
key, value = tuple(__line[:2]), __line[2:]
if key in self.combine:
self.combine[key] = self.combine[key] + value
else:
self.combine[key] = value
if key in self.counter:
self.counter[key] = self.counter[key] + 1
else:
self.counter[key] = 1
for k1, v1 in self.counter.items():
if v1 >= 2:
self.result[k1] = self.combine[k1]
print()
return self.result
if __name__ == '__main__':
files = ['ds1.txt', 'ds2.txt']
print("Started at: {}{}".format(datetime.datetime.now(), '\n'))
print('Initial data:')
fck = FindCommKey()
for f in files:
fck.find_common_key(f)
print("Write to dic finished at: {}{}".format(datetime.datetime.now(), '\n'))
print('Result set:')
for k, v in fck.result.items():
print(','.join(map(str, k)), tuple(v))
print("{}Finished at: {}".format('\n', datetime.datetime.now()))

How to prevent Selenium from opening a pop-up to save the file?

I'm scraping the site Quicker.com but every time getting an error on random pages.
The error is:
UnexpectedAlertPresentException: Alert Text: C:\Users\HEYPIL~1\AppData\Local\Temp\Pkwnr4IA.php.part could not be saved, because the source file could not be read.
Try again later, or contact the server administrator.
<super: <class 'WebDriverException'>, <UnexpectedAlertPresentException object>>
My code:
from selenium import webdriver
import csv
import re
import hashlib
from selenium.common.exceptions import UnexpectedAlertPresentException
from selenium.common.exceptions import WebDriverException
import socket
import time
import datetime
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
date = st.encode('utf8')
IPAdd = socket.gethostbyname(socket.gethostname())
counter = 5
initial = []
base = "http://mumbai.quikr.com/Individual/0-50000000/Houses-Apartments-for-Sale/w1072?imageAds=Y&l=You_are-Price"
string = "&page="
while(counter == 5 or counter < 40):
base2 = base+string+str(counter)
if (counter < 39):
initial.append(base2)
elif(counter == 40):
initial.append(base)
else:
base2 = base
counter += 1
for n in initial:
result = []
driver = webdriver.Firefox()
driver.get(n)
main_page = '//a[#class="adttllnk unbold"]'
for a in driver.find_elements_by_xpath(main_page):
l = a.get_attribute('href')
result.append(l)
print len(result)
driver.close()
for url in result:
try:
driver = webdriver.Firefox()
driver.get(url)
items = []
desc_path = '//div[#id="ad_description"]'
img_path = '//div[#class="bigImg_wapp"]//img[#src]'
prop = '//div[#itemprop="name"]//h1[#class="ad_title translate"]'
amenities = '//div[#class="ad-atrbt-panel"]//span[#class="ad-atrbt-val"]//span[#class="attribVal newattribVal"]'
phone = '//span[#class="NoVerified-Text"]'
for x1 in driver.find_elements_by_xpath(img_path):
img = (x1.get_attribute('src')).encode('utf8')
print '\n'+img
for x2 in driver.find_elements_by_xpath(desc_path):
desc = (x2.text).encode('utf8')
print '\n'+ desc
for x3 in driver.find_elements_by_xpath(prop):
prop_title = (x3.text).encode('utf8')
print '\n'+prop_title
for x4 in driver.find_elements_by_xpath(amenities):
value = (x4.text).encode('utf8')
items.append(value)
print '\n'
print items
locality = items[0]
locality1 = locality.encode('utf8')
a = (locality1 if (isinstance(locality1,int) == False) else "")
bhk = items[1]
bhk1 = bhk.encode('utf8')
if(bhk1 == "4+ BHK"):
b = "4"
else:
bhk2 = [int(z) for z in bhk1.split() if z.isdigit()]
b = ((str(bhk2).strip('[')).strip(']')).strip()
furnish = items[2]
if(isinstance(furnish,int) == False ):
furnish1 = furnish.encode('utf8')
if((furnish1 == "Semi-Furnished") or (furnish1 == "Unfurnished") or (furnish1 == "Fully Furnished") or (furnish1 == "Unfurnished,Unf...")):
c = furnish1
else:
d = furnish1
elif(isinstance(furnish,int) == True):
furnish1 = furnish.encode('utf8')
d = furnish1
else:
c = ""
sqft = items[3]
if(isinstance(sqft,int)==True):
sqft1 = [int(xyz) for xyz in sqft.split() if xyz.isdigit()]
sqft2 = ((str(sqft1).strip('[')).strip(']')).strip()
d = sqft2.encode('utf8')
elif(isinstance(sqft,int)==False):
sqft1 = sqft.encode('utf8')
if((sqft1 == "Semi-Furnished") or (sqft1 == "Unfurnished") or (sqft1 == "Fully Furnished") or (sqft1 == "Unfurnished,Unf...")):
c = sqft1
else:
d = sqft1
else:
d = ""
atz = '\t'
print a,atz,b,atz,c,atz,d
for x5 in driver.find_elements_by_xpath(phone):
biz = (((x5.text).lstrip('+91')).strip()).encode('utf8')
if(len(biz)== 9):
biz_phone = '9'+biz
elif(len(biz) < 7 and len(biz) > 4):
biz_phone = '080'+biz
elif(len(biz) > 9 or len(biz) < 12):
biz_phone = biz
elif(len(biz) == 4 or len(biz) < 4):
biz_phone = biz.strip(biz)
else:
print '\nInvalid Business_phone'
print '\n'+biz_phone
driver.close()
hash_key = hashlib.md5("marketing#"+biz_phone+".com"+"Individual"+prop_title).hexdigest()
unique_key = ('I_'+hash_key).encode('utf8')
except (NameError, IndexError, WebDriverException, UnexpectedAlertPresentException) as e:
print "Failed to open: "+url
driver.close()
fieldname = ['Date','URL']
with open("C:\Users\Heypillow\Desktop\scrapWork\properties\\Failed_to_open_url.csv",'a') as h:
write = csv.DictWriter(h,fieldnames=fieldname,lineterminator = '\n')
write.writerow({'Date':date,
'URL':url})
I've blocked the pop-up in Firefox() but yet a pop-up is coming which addressing me to save a .php file and raises this exception.
I've already used that exception in the "except" part yet it's interrupting the code to work further and it's getting stopped just after this exception rises.
So, every time this exception rises, I have to restart the program. Thus I would like to download all the data by running the code through out the night,which is impossible with this circumstances…
How can I prevent this pop-up from opening?
(If I would have been able to upload a screenshot of the pop-up,it would have been easier to understand it.)

check entry inputs in tkinter using a function

I trying to create physics calculator using python tkinter but I find it quite difficult. I have done this calculator in Command line interface but I a bit different with tkinter. basically, I have 5 entry boxes and above each one of them a button. the user will insert values in three of them and should press the button on top of each unknown value to make the calculation and get the result. my main issue is how can I create a function that evaluates the inputs in my entry boxes and make the calculation then print the results inside the entry box. I made some coding but unfortunately the operation is not working due to few mistakes.
here is my coding part:
from Tkinter import *
import math
class calculator():
def is_positive_number(number): # validation function
if number <= 0:
return False
else :
return True
def value_of_time(prompt):
while True: # loop command for time
try:
valid = False
while not valid:
value = float((prompt))
if is_positive_number(value):
valid = True
return value
else :
valid = False
print ('I donot know what is happening')
except ValueError:
print("Oops, unfortunately this is a wrong input, please try again.")
#better try again... Return to the start of the loop
continue
else:
#value was successfully parsed!
#we're ready to exit the loop.
break
def input_of_box(prompt):
while True: # loop for initial velocity
try:
value = float(input(prompt))
return value
except ValueError:
print("Oops, we are you not typing a number, please try again.")
#better try again... Return to the start of the loop
continue
else:
#value was successfully parsed!
#we're ready to exit the loop.
break
# def minput(numberofinput):
if numberofinput == 1:
t = value_of_time("Enter the time that takes an object to accelerate in seconds:")
return
elif numberofinput == 2:
u = input_of_box("Enter the initial velocity in m/s:")
return
elif numberofinput == 2:
v = input_of_box("Enter the final velocity in m/s:")
return
def my_calculation(mvariables): # this function is to operate the calculation
if mvariables == 1:
a = (v-u) /(t)
mentery1 = a
return
elif mvariables == 2:
v = u + a*t
mentery2 = v
return
elif mvariables == 3:
u = a*t - v
mentery3 = t
elif mvariables == 4:
t = (v - u)/a
mentery3 = t
return
elif mvariables == 5:
s = (v**2-u**2)/2*a
mentery4 = s
else:
print ('there is an error')
cal = Tk()
cal.configure(background='sky blue')
a = StringVar()
u = StringVar()
v = StringVar()
t = StringVar()
s = StringVar()
cal.geometry('650x420+350+225')
cal.title('Main Menu')
# here we start greating buttons and entry boxes
m_label = Label(text='Calculator',fg = 'Navy', font=("Helvetica", 20,"bold italic"), bg='sky blue')
m_label.pack()
button1 = Button(cal,text='A',fg='white',bg='dark green',bd =3, width=4, command= lambda : my_calculation(1))
button1.place(x=92,y=210)
mentery1 = Entry(cal, textvariable = a ,width=10,bd =3)
mentery1.place(x=82,y=240)
button2 = Button(cal,text='U',fg='white',bg='dark green',bd =3, width=4, command= lambda : my_calculation(3))
button2.place(x=192,y=210)
mentery2 = Entry(cal, textvariable = u ,width=10,bd =3)
mentery2.place(x=182,y=240)
button3 = Button(cal,text='V',fg='white',bg='dark green',bd =3, width=4, command= lambda : my_calculation(2))
button3.place(x=292,y=210)
mentery3 = Entry(cal, textvariable = v ,width=10,bd =3)
mentery3.place(x=282,y=240)
button4 = Button(cal,text='T',fg='white',bg='dark green',bd =3, width=4,command= lambda : my_calculation(4))
button4.place(x=392,y=210)
mentery4 = Entry(cal, textvariable = t ,width=10,bd =3)
mentery4.place(x=382,y=240)
button5 = Button(cal,text='S',fg='white',bg='dark green',bd =3, width=4,command= lambda : my_calculation(5))
button5.place(x=492,y=210)
mentery5 = Entry(cal, textvariable = s , width=10,bd =3)
mentery5.place(x=482,y=240)
# end of button commands
app = calculator()
app.mainloop()
For validating the input, do the following:
def returnValidatedInput(entry):
value = entry.get() # Get the text in the 'entry' widget
evaluation = eval(value) # Evaluate 'value'
return evaluation
And for inserting the answers into the entries (it's not called printing the answers into the entries):
def insertAnswer(entry, answer):
entry.delete(0, 'end') # Be sure the entry is empty, if it is not, clear it
entry.insert(END, str(answer)) # Insert the answer into the 'entry' widget.

(Python) Shelve + try: how to search for a key and set it if it doesn't exists without repeating code?

To store the user work folders permanently, I'm using shelve. And to know if the user has the folders configured I'm using a similar code 3 times:
pastaUsuario = os.getenv('HOMEDRIVE') + os.getenv('HOMEPATH')
pastaPrincipal = pastaUsuario + '\\rev'
pastaConfig = pastaPrincipal + '\\config'
config = shelve.open(pastaConfig + '\\config.db')
try:
pastaIsometricosSpooler = config['pastaIsometricosSpooler']
except Exception:
config['pastaIsometricoSpooler'] = raw_input('Digite o caminho da pasta de extração do Spooler: ')
pastaIsometricosSpooler = config['pastaIsometricosSpooler']
finally:
config.close()
config = shelve.open(pastaConfig + '\\config.db')
try:
ultimoIso = config['ultimoIso']
except Exception:
config['ultimoIso'] = raw_input('Digite o tag do isométrico a ser revisado: ')
ultimoIso = config['ultimoIso']
finally:
config.close()
config = shelve.open(pastaConfig + '\\config.db')
try:
ultimaRev = config['ultimaRev']
except Exception:
config['ultimaRev'] = raw_input('Digite a nova revisão: ')
ultimaRev = config['ultimaRev']
finally:
config.close()
How to avoid repeating the almost identical code?
I tried to use the "for" statement with a list:
config = shelve.open(pastaConfig + '\\config.db')
for x in ['pastaIsometricosSpooler', 'ultimoIso', 'ultimaRev']:
try:
x = config[x]
except Exception:
config[x] = raw_input()
x = config[x]
finally:
config.close()
But the variable set doesn't work because of quotes (eg.: 'ultimaRev' = config['ultimaRev'])
Sorry for my bad english!
This is probably best done by using a function rather than trying to make the same code work in a loop. Adapting what you have:
def getconfig( x, prompt ):
try:
theconf= config[x]
except Exception:
config[x] = raw_input( prompt )
theconf= config[x]
return theconf
Then you can use it three times:
config = shelve.open(pastaConfig + '\\config.db')
ultimaRev = getconfig( 'ultimaRev', 'Digite a nova revisão: ')
ultimoIso = getconfig( 'ultimoIso', 'Digite o tag do' )
pastaIsometricosSpooler = getconfig('pastaIsometricosSpooler', 'Digite o caminho da' )
config.close()