First thing first, code is list below,
import sys
import os
import latexmake
import mysql.connector
conn = mysql.connector.connect(user='root',password='oilwell',host='localhost',database='sqlpush1')
with conn:
mycursor = conn.cursor()
mycursor=execute("SELECT DATE,oil,gas,oilprice,gasprice,totrev FROM results WHERE DATE BETWEEN '2011-01-01' AND '2027-12-01'")
rows = mycursor.fetchall()
a.write("\\documentclass{standalone}\\usepackage{booktabs}\n\n\\usepackage{siunitx}\r \n\
\r\n\\begin{document}\r\n\\begin{tabular}{ccS[table-format = 5.2]} \\\\ \\toprule\r")
a.write("Date & Oil & Gas & Oil price & Gas price & Total Revenue \\\\ \\midrule \r")
for row in rows:
a = open("testtest.tex", "w")
a.write("" + str(row[0]) + " & " + str(row[1]) + " & " + str(row[2]) + " & " + str(row[3]) + " & " + str(row[4]) + " & " + str(row[5]) + " \\\\ \r")
a.write("\\bottomrule \\end{tabular}\r\\end{document}")
a.close
print os.path.getsize("testtest.tex")
os.system('latexmk.py -q testtest.tex')
mycursor.close()
conn.close()
after run IDLE, an error called "Invalid Syntax" pop up on line "os.path.getsize"
I did import os at very beginning, and I don't know why.
Appreciated your kind help.
Regards,
Cheng
It's not the os.path.getsize that's the problem, it's the print. You're using Python 3 and print is now a function, and therefore needs parentheses.
print(os.path.getsize("testtest.tex"))
Also, it'd be nice (though admittedly, you'd never notice in this script) if you actually called close rather than just referencing it:
a.close()
Related
Im trying to concatenate the date and code entity in order to read a database, but I can't. Here is my code. Its comment a line where my code works but im not concating the date and code entity. Please, I want to help me changing my code.
# PAQUETES
import os
import pandas as pd
import psycopg2 as pg2
entidadinput="00022"
fechainput="202202"
tabla="admcrcd.v_rcd_anexo6"
variables="*"
userRCD=os.getenv('JUPYTERHUB_USER')
con = pg2.connect(user=userRCD,
password="post",
host="172.XX.ABC.EF",
port="3456",
database="BDCreditos")
with con:
cur=con.cursor() #vesel
#cur.execute("SELECT " + variables + " from " + tabla + " WHERE fecha='202202'"+" AND cdg_emp='00022'") # This works
cur.execute("SELECT " + variables + " from " + tabla + " WHERE fecha= '" + fechainput +"' AND cdg_emp='" + entidadinput + "'") # This doesnt work
#cur.execute("SELECT * from admcrcd.v_rcd_anexo6 WHERE fecha=202204")
version = cur.fetchone()[0]
print(version)
BD = cur.fetchall()
#for row in rows:
# print(f"{row[0]} {row[1]} {row[2]}")
con.close()
First, the second line should import os. I regenerated both connection strings and the only difference I found is that the string not working has one more space before fecha=, which should not cause the problem normally. But otherwise, the two strings are the same. You can try that (code is as below).
cur.execute("SELECT " + variables + " from " + tabla + " WHERE fecha='" + fechainput +"' AND cdg_emp=" + entidadinput) # This does not work
Problem houses of pset7, cs50. The output of my program is as per requirement but my code doesn't qualify 5 out of 6 tests. I have tried a lot but couldn't find the mistake. Please help me out.
import.py
import sys
import cs50
import csv
if (len(sys.argv) !=2):
print("Error: Incorrect Command-line Arguments")
exit (1)
db =cs50.SQL("sqlite:///students.db")
db.execute ("DROP TABLE students")
db.execute ("CREATE TABLE IF NOT EXISTS students (first TEXT,middle TEXT,last TEXT,house TEXT,birth NUMERIC)")
with open ("characters.csv", "r") as characters:
reader = csv.DictReader(characters,delimiter = ",")
for row in reader:
name = row["name"]
name_list = name.split()
if (len(name_list) == 3):
first = name_list[0]
middle = name_list[1]
last = name_list[2]
elif (len(name_list) == 2):
first = name_list[0]
middle = None
last = name_list[1]
house = row["house"]
birth = int (row["birth"])
db.execute("INSERT INTO students (first,middle,last,house,birth) VALUES (?,?,?,?,?)",first,middle,last,house,birth)
roster.py
import sys
import cs50
import csv
import sqlite3
if (len(sys.argv) !=2):
print("Error: Incorrect Command-line Arguments")
exit (1)
user_house = sys.argv[1]
db = cs50.SQL("sqlite:///students.db")
list_dicts = db.execute("SELECT first, middle, last, birth FROM students WHERE house = (?) ORDER BY last, first", (user_house))
for row in list_dicts:
if (row ["middle"] == None):
print(row["first"] + " " + row["last"] + ", born" + " " + str(row["birth"]) )
else:
print(row["first"] + " " + row["middle"] + " " + row["last"] + ", born" + " " + str (row["birth"]))
Your students table does not match the schema supplied in the distro code.
I seem to be having an issue with looping through the data that I pulled from a url in my Alexa skill, here is my sample code:
def get_elevator_status():
session_attributes = {}
card_title = "Septa Elevator Status"
reprompt_text = ""
should_end_session = False
response = urllib2.urlopen(API_BASE_URL + "/elevator")
septa_elevator_status = json.load(response)
for elevators in septa_elevator_status['results']:
speech_output = "The following elevators are out of service." "On " + elevators['line'] + " at station " + elevators['station'] + " the " + elevators['elevator'] + " elevator has " + elevators['message']
If I run the code in python shell and print out the results (if there are multiple outages) it prints out all lines. But when I test my Alexa skill and ask for outages it only reports back one result even though there are multiple elevator outages. Am I missing something for this to work? Should this code loop through and say all results found right?
can you post the 'response' json, my guess is that the json is not formed correctly
While looping through the result set everytime you are overwriting speech_output with that particular elevators. Instead, you have to concatenate every result to speech_output.
for elevators in septa_elevator_status['results']:
speech_output = speech_output + " <s> The following elevators are out of service." "On " + elevators['line'] + " at station " + elevators['station'] + " the " + elevators['elevator'] + " elevator has " + elevators['message'] + "</s>"
<s> is the sentence tag, use it only if you are using SSML.
I built a relation data model in Oracle and now creating a GUI using Python. I need a SQL statement to execute in my IDE but get a cx_Oracle.DatabaseError: ORA-00936: missing expression error message. This is a CTE that runs fine in TOAD and when I remove the CTE and put in a simple SQl statement it executes fine.
I can build a view in my DB and do a select * from but I don't want to go that way.
I'm new to Python so I'm sure there is a better way to do this.
import cx_Oracle
con = cx_Oracle.connect('Example', 'Example', "Example")
cur = con.cursor()
statement = ("with r1 as (" +
" select " +
" r.PARENT_ITEM_id, " +
" D.SC_ID, " +
" --F.TONS" +
" SUM(ROUND(F.TONS*Pic_Distro*2000*s.stk_lvl_mult)) as Stocking_Lvl" +
" from PIC_DISTRO_TBL D" +
" Left Join Part_Velocity_TBL P on (P.item_ID = D.Item_ID and D.SC_ID = P.SC_ID)" +
" Left Join Forecast_TBL F on (D.Bucket_ID = F.Bucket_ID and D.SC_ID =F.SC_ID)" +
" left join Stock_lvl_tbl S on (S.Velocity_id = P.VELOCITY_ID)" +
" left join item_tbl I on (i.item_ID = D.ITEM_ID)" +
" left join parent_item_tbl R on (r.PARENT_ITEM_id = i.PARENT_ITEM_id)" +
" Where F.MTH = '4'" +
" and F.YEAR = '2017'" +
" and P.Velocity_id in ('A','B','C')" +
" and D.SC_ID in ('01','02')" +
" -- and SUM(ROUND(F.TONS*Pic_Distro*2000*s.stk_lvl_mult)) > 0" +
" Group by " +
" r.PARENT_ITEM_id, D.SC_ID " +
" Order by " +
" D.SC_ID DESC, Stocking_lvl DESC" +
")," +
"R2 as (" +
"select r.Parent_Item_ID, o.SC_ID, " +
"coalesce(sum(avail_wt), 0) as Avail_Wt" +
" from" +
" open_inv_tbl O" +
" left join item_tbl I on (i.item_ID = o.ITEM_ID)" +
" left join parent_item_tbl R on (r.PARENT_ITEM_id = i.PARENT_ITEM_id)" +
" Where r.Parent_item_ID is not null" +
" Group by r.Parent_Item_ID,o.SC_ID)" +
"select " +
" r1.PARENT_ITEM_id, " +
" R1.SC_ID, R1.Stocking_Lvl , " +
" coalesce(R2.Avail_wt, 0 ) as Avail_Wt, " +
" coalesce(R2.Avail_wt/R1.Stocking_Lvl, 0) as Precantage" +
" From R1" +
" left join R2 on (R1.parent_item_id = R2.parent_item_id and R1.Sc_ID = R2.Sc_ID) " +
" Where R1.Stocking_lvl > '0' " +
" Order by SC_id Desc, Stocking_Lvl Desc)" )
cur.arraysize = 2000
cur.execute(statement)
Python offers you multi-line strings, when wrapped in triple quotes.
Try a execute a single string and review your query being correct.
statement = """
with r1 as (
select
r.PARENT_ITEM_id,
D.SC_ID,
--F.TONS
...
"""
cur.execute(statement)
I've been working with python for the past few days, and started working on a project. Currently trying to figure out how to execute the same function using multiple variables (In this case, Stock symbols). Preferably with one input() separated with a comma or something. I've hit a snag with this last part though. Can anyone point me in the direction of where to go next? (Running the same function with multiple variables at the same time.)
Here is my code:
#Google + Yahoo Finance Stock Lookup
from googlefinance import getQuotes
from yahoo_finance import Share
import googlefinance
import datetime, time
import os
from datetime import datetime
tDate = datetime.now().strftime('%Y-%m-%d')
print (tDate)
tDateConv = str(tDate)
try:
os.chdir('/Users/Jakes_Macbook/Desktop/Python/Stocks')
except Exception:
print('Default Path does not exsist, make sure your directory is right.')
pass
run = True
while run == True:
print('You are currently storing the file in ')
print(os.getcwd())
print('type "yes" to continue')
confirm = input()
if confirm == 'yes':
print ('ok\n')
try:
os.makedirs(tDateConv)
except Exception:
pass
os.chdir(tDateConv)
print('File will be saved to:')
print(os.getcwd())
break
else:
print('Where do you want to store the file?')
changeDir = input()
os.chdir(changeDir)
print('What Stock or Stocks would you like to look up?')
stockSymbol = input()
def runStocks():
print (" ")
print ("Stock Symbol: " + stockSymbol)
stockSymbolYhoo = Share(stockSymbol)
stockFile = open(str(stockSymbol)+'.txt', 'a')
dicStored = googlefinance.getQuotes(stockSymbol)[0]
numStoredPrice = float(dicStored['LastTradePrice'])
print('Stock Open: ' + stockSymbolYhoo.get_open())
print ("Stored Price: " + str(numStoredPrice))
stockFile.write(str("\n" + "Stock Symbol: " + stockSymbol + "\n"))
stockFile.write(str("\n" + "Open Price: " + stockSymbolYhoo.get_open() + "\n"))
stockFile.write(str("Stored Price: " + str(numStoredPrice)+'\n'))
runs = 0
while runs < 5:
stor = googlefinance.getQuotes(stockSymbol)[0]
price = stor['LastTradePrice']
print(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) + " | " + price)
stockFile.write(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) + " | Price " + price + ' \n')
numPrice = float(price)
if numPrice < numStoredPrice*float(.995):
print ("buy")
time.sleep(5)
runs = runs + 1
stockFile.close()
runStocks()
My goal is to have each stock symbol, that is inputted, create its own file in the folder for today. I'm pretty sure i can figure out how to do that once i get multiple functions going. Thanks in advance.
Also, let me know if you have any important suggestions or best practices. This is like my second day working with python. Thanks Again.
Just pass them into the function:
# Note the definition was updated to be able to pass in a stockSymbol
def runStocks(stockSymbol):
print (" ")
print ("Stock Symbol: " + stockSymbol)
stockSymbolYhoo = Share(stockSymbol)
stockFile = open(str(stockSymbol)+'.txt', 'a')
dicStored = googlefinance.getQuotes(stockSymbol)[0]
numStoredPrice = float(dicStored['LastTradePrice'])
print('Stock Open: ' + stockSymbolYhoo.get_open())
print ("Stored Price: " + str(numStoredPrice))
stockFile.write(str("\n" + "Stock Symbol: " + stockSymbol + "\n"))
stockFile.write(str("\n" + "Open Price: " + stockSymbolYhoo.get_open() + "\n"))
stockFile.write(str("Stored Price: " + str(numStoredPrice)+'\n'))
stockSymbols = input("Enter stock symbols separated by commas").split(",")
for stockSymbol in stockSymbols:
runStocks(stockSymbol) # Call your function in a loop