In line 81, I get an error: 'str' object has no attribute 'getCode'
but then I don't understand why lines 80-83 work fine.
I need to implement reading and writing an xml file.
The deliveries class has 2 fields of other classes (parts and providers).
I don't understand how to make a mistake, please give me a hint.
import os,xml.dom.minidom
from data import data
class dataxml(data):
def read(self):
dom=xml.dom.minidom.parse(self.getInp())
dom.normalize()
for node in dom.childNodes[0].childNodes:
if (node.nodeType==node.ELEMENT_NODE)and(node.nodeName=='providers'):
code,provider,title,adres,telephone=0,"","","",""
for t in node.attributes.items():
if t[0]=="code":code=int(t[1])
if t[0]=="provider":provider=t[1]
if t[0]=="title":title=t[1]
if t[0]=="adres":adres=t[1]
if t[0]=="telephone":telephone=t[1]
self.getLib().createProviders(code,provider,title,adres,telephone)
if (node.nodeType==node.ELEMENT_NODE)and(node.nodeName=='parts'):
code,title,articule,price,note=0,"",0,0,""
for t in node.attributes.items():
if t[0]=="code":code=int(t[1])
if t[0]=="title":title=t[1]
if t[0]=="articule":articule=int(t[1])
if t[0]=="price":price=int(t[1])
if t[0]=="note":note=t[1]
self.getLib().createParts(code, title, articule, price, note)
if (node.nodeType==node.ELEMENT_NODE)and(node.nodeName=='deliveries'):
code,providers,parts,guantity,date=0,None,None,0,""
for t in node.attributes.items():
if t[0]=="code":code=int(t[1])
if t[0]=="guantity":guantity=int(t[1])
if t[0]=="providers":
providers=self.getLib().getProviders(int(t[1]))
if t[0]=="parts":
parts=self.getLib().getParts(int(t[1]))
if t[0]=="date":date=t[1]
self.getLib().createDeliveries(code,providers,parts,guantity,date)
def write(self):
dom=xml.dom.minidom.Document()
root=dom.createElement("shop")
dom.appendChild(root)
for a in self.getLib().getProvidersList():
pro=dom.createElement("providers")
pro.setAttribute('code',str(a.getCode()))
pro.setAttribute('provider',a.getProvider())
pro.setAttribute('title',a.getTitle())
pro.setAttribute('adres',a.getAdres())
pro.setAttribute('telephone',a.getTelephone())
root.appendChild(pro)
for p in self.getLib().getPartsList():
par=dom.createElement("parts")
par.setAttribute('code',str(p.getCode()))
par.setAttribute('title',p.getTitle())
par.setAttribute('articule',str(p.getArticule()))
par.setAttribute('price',str(p.getPrice()))
par.setAttribute('note',p.getNote())
root.appendChild(par)
for b in self.getLib().getDeliveriesList():
de=dom.createElement("deliveries")
de.setAttribute('code',str(b.getCode()))
de.setAttribute('guantity',str(b.getGuantity()))
de.setAttribute('date',b.getDate())
if b.getProviders():
pc=b.getProviders().getCode()
else:pc=""
de.setAttribute('providers',str(pc))
if b.getParts():
ppc=b.getParts().getCode() #'str' object has no attribute 'getCode'
else:ppc=""
de.setAttribute('parts',str(ppc))
root.appendChild(de)
f = open(self.getOut(),"w")
#f.write(dom.toprettyxml(encoding='utf-8'))
f.write(dom.toprettyxml())
I tried to do this, but there were only more mistakes.
for b in self.getLib().getDeliveriesList():
de=dom.createElement("deliveries")
de.setAttribute('code',str(b.getCode()))
de.setAttribute('guantity',str(b.getGuantity()))
de.setAttribute('date',b.getDate())
de.setAttribute('providers',b.getProviders()) #
de.setAttribute('parts',b.getParts()) #
Related
I have the following block of code.
class ChooseBook():
bookprice=2
def getqty(self, sv):
if self.txtbookqty.get()=="":
self.qty=0
else:
self.qty=int(self.sv.get())
self.txtbookprice.delete(0,END)
#print(self.qty)
self.txtbookprice.insert(0,self.qty*self.bookprice)
def on_CPOname_change(self,value,op,op2):
stname=self.comboBookname.get()
name=stname[1:-1]
book_data=Fun_Select("SELECT book_price FROM book_record WHERE book_name='"+name+"'")
#print(book_data)
self.bookprice=int(book_data[0][0])
def on_date_change(self,day):
if self.txtdaysborrowed.get()=="":
self.dayadd=0
else:
self.dayadd=int(self.day.get())
date=self.txtborrowdate.get()
self.dayindate=int(date[8:10])
self.yearindate=int(date[0:4])
self.monthindate=int(date[5:7])
if self.dayindate+self.dayadd > 31:
self.monthindate=self.monthindate+1
if self.monthindate > 12:
self.yearindate+=1
self.txtrd.insert(0,self.dayindate+'-'+self.monthindate+'-'+self.yearindate)
def __init__(self):
today_date=datetime.date.today()
win=Tk()
win.title("Choose book type")
win.geometry("600x800")
v=StringVar()
d=StringVar()
v.trace('w', self.on_CPOname_change)
self.day=StringVar()
self.day.trace('w',lambda name, index, mode, day=self.day: self.on_date_change(day))
self.sv = StringVar()
self.sv.trace("w", lambda name, index, mode, sv=self.sv: self.getqty(sv))
Label(win,text="Choose Book Name").grid(row=0,column=0,padx="1.5c",pady="1c")
Label(win,text="Enter Book Quantity").grid(row=1,column=0,padx="1.5c",pady="1c")
Label(win,text="Total Book Price").grid(row=2,column=0,padx="1.5c",pady="1c")
Label(win,text="Borrowed Date").grid(row=3,column=0,padx="1.5c",pady="1c")
Label(win,text="Days borrowed").grid(row=4,column=0,padx="1.5c",pady="1c")
Label(win,text="Return Date").grid(row=5,column=0,padx="1.5c",pady="1c")
Label(win,text="Choose Employee Name").grid(row=6,column=0,padx="1.5c",pady="1c")
Label(win,text="Choose Customer Name").grid(row=7,column=0,padx="1.5c",pady="1c")
#bookname
self.comboBookname=ttk.Combobox(win, textvar=v)
self.comboBookname["values"]=Fun_Select("SELECT book_name FROM book_record")
self.comboBookname.grid(row=0,column=1,pady="1c")
#bookqty
self.txtbookqty=Entry(win,textvariable=self.sv)
self.txtbookqty.grid(row=1,column=1,pady="1c")
#bookprice
self.txtbookprice=Entry(win)
self.txtbookprice.grid(row=2,column=1,pady="1c")
#borrowdate
self.txtborrowdate=Entry(win,textvariable=d,state=DISABLED)
d.set(today_date)
self.txtborrowdate.grid(row=3,column=1,pady="1c")
#daysborrowed
self.txtdaysborrowed=Entry(win,textvariable=self.day)
self.day.set(0)
self.txtdaysborrowed.grid(row=4,column=1,pady="1c")
#returndate
self.txtrd=Entry(win)
self.txtrd.grid(row=5,column=1,pady="1c")
#employeename
self.comboEmployeename=ttk.Combobox(win)
self.comboEmployeename["values"]=Fun_Select("SELECT employee_name FROM employees")
self.comboEmployeename.grid(row=6,column=1,pady="1c")
#customername
self.comboCustomername=ttk.Combobox(win)
self.comboCustomername["values"]=Fun_Select("SELECT customer_name FROM customers")
self.comboCustomername.grid(row=7,column=1,pady="1c")
Button(win,text="Exit",width=10,command=win.destroy).grid(row=8,column=0,padx="1.5c",pady="1c")
Button(win,text="Save",width=10,command=None).grid(row=8,column=1,padx="1.5c",pady="1c")
win.mainloop()
ChooseBook()
But I get always error which says: AttributeError: 'ChooseBook' object has no attribute 'txtrd'. It seems that problem is somewhere at self.txtrd.insert(0,self.dayindate+'-'+self.monthindate+'-'+self.yearindate)
Also i'm quite new so my code might be very messy.
Here is a quick fix to THIS problem, just move the declaration of self.txtrd above self.day.set(0).
def __init__(self):
....#same bunch of code
self.txtrd=Entry(win)
self.txtrd.grid(row=5,column=1,pady="1c")
....#same bunch of code
self.day.set(0)
....#same bunch of code
You are using trace with self.day which means whenever you change the value of StringVar() it triggers the function, and later in code you are saying self.day.set(0)(value changing) so the trace becomes active and the function is called, before the self.txtrd is defined and hence the error.
Though after solving this error you will get a ValueError at:
self.txtrd.insert(0,self.dayindate+'-'+self.monthindate+'-'+self.yearindate)
To fix that do simple type casting like:
self.txtrd.insert(0,str(self.dayindate)+'-'+str(self.monthindate)+'-'+str(self.yearindate))
Though I highly doubt if you might get another error(unexpected behavior) over setting the values for the Combobox, anyway that can be asked as a new post, as one post should only focus around one problem.
Im brand new to python and coding, im trying to get below working.
this is test code and if I can get this working I should be able to build on it.
Like I said im new to this so sorry if its a silly mistake.
# coding=utf-8
import ops # Import the OPS module.
import sys # Import the sys module.
import re
# Subscription processing function
def ops_condition (o):
enter code herestatus, err_str = o.timer.relative("tag",10)
return status
def ops_execute (o):
handle, err_desp = o.cli.open()
print("OPS opens the process of command:",err_desp)
result, n11, n21 = o.cli.execute(handle,"return")
result, n11, n21 = o.cli.execute(handle,"display interface brief | include Ethernet0/0/1")
match = re.search(r"Ethernet0/0/1\s*(\S+)\s*", result)
if not match:
print("Could not determine the state.")
return 0
physical_state = match[1] # Gets the first group from the match.
print (physical_state)
if physical_state == "down":
print("down")
result = o.cli.close(handle)
else :
print("up")
return 0
Error
<setup>('OPS opens the process of command:', 'success')
Oct 17 2018 11:53:39+00:00 setup %%01OPSA/3/OPS_RESULT_EXCEPTION(l)[4]:Script is test.py, current event is tag, instance is 1515334652, exception reason is Trac eback (most recent call last):
File ".lib/frame.py", line 114, in <module>
ret = m.ops_execute(o)
File "flash:$_user/test.py", line 22, in ops_execute
physical_state = match[1] # Gets the first group from the match.
TypeError: '_sre.SRE_Match' object has no attribute '__getitem__'
The __getitem__ method for the regex match objects was only added since Python 3.6. If you're using an earlier version, you can use the group method instead.
Change:
physical_state = match[1]
to:
physical_state = match.group(1)
Please refer to the documentation for details.
Consider this basic example for the use of a with statement from Jeff Knupp's blog:
class File():
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.open_file = open(self.filename, self.mode)
return self.open_file
def __exit__(self, *args):
self.open_file.close()
I have a testfile which contains two lines, 'ABC' and 'DEF'. Everything works as expected:
with File('/tmp/testfile','r') as f:
txt = [x.strip() for x in f.readlines()]
print(txt)
# ['ABC', 'DEF']
Calling a class method outside the with block gives me the expected error:
f.readlines()
ValueError Traceback (most recent call last)
in ()
----> 1 f.readlines()
ValueError: I/O operation on closed file.
Now to my question:
How can I achieve the same behavior with a gdal object instead of a file?
I have a class method, which should read data from disk and put it into a gdal raster for further processing. Once this is done, I would like to close the generated gdal raster appropriately. Normally this is done with setting it to None and with using gdal.Unlink.
However, when I put everything into a context structure as in the previous example, I can still interact with the dataset outside of the with block.
Here's a reproducible example:
class Raster:
'''Raster class with sidelength s'''
def __init__(self,s):
self.sidelength = s
def __enter__(self):
# create raster in memory
driver = gdal.GetDriverByName('GTiff')
self.raster = driver.Create('/vsimem/inmem.tif', self.sidelength, self.sidelength, 1, gdal.GDT_Float32)
self.raster.GetRasterBand(1).WriteArray(np.random.rand(self.sidelength,self.sidelength))
return self.raster
def __exit__(self, *args):
# close file and unlink
self.raster = None
gdal.Unlink('/vsimem/inmem.tif')
The with block works as expected:
with Raster(5) as r:
print(r)
# <osgeo.gdal.Dataset; proxy of <Swig Object of type 'GDALDatasetShadow *' at 0x7f8078862ae0> >
But after the block the object is still there and I can still read the values:
print(r)
#<osgeo.gdal.Dataset; proxy of <Swig Object of type 'GDALDatasetShadow *' at 0x7f8078044a20> >
print(r.ReadAsArray())
#[[0.2549882 0.80292517 0.23358545 0.6284887 0.7294142 ]
# [0.9310723 0.21535267 0.9054575 0.60967094 0.9937953 ]
# [0.69144976 0.01727938 0.16800325 0.61249655 0.1785022 ]
# [0.16179436 0.43245795 0.7042811 0.4809799 0.85534436]
# [0.67751276 0.7560658 0.9594516 0.6294476 0.3539126 ]]
You cannot really close a gdal dataset while keeping a reference to it. You can keep a reference to the Raster instance instead and use r.raster to access the dataset inside the with block.
class Raster:
'''Raster class with sidelength s'''
def __init__(self,s):
self.sidelength = s
def __enter__(self):
# create raster in memory
driver = gdal.GetDriverByName('GTiff')
self.raster = driver.Create('/vsimem/inmem.tif', self.sidelength, self.sidelength, 1, gdal.GDT_Float32)
self.raster.GetRasterBand(1).WriteArray(np.random.rand(self.sidelength,self.sidelength))
return self
def __exit__(self, *args):
# close file and unlink
self.raster = None
gdal.Unlink('/vsimem/inmem.tif')
with Raster(5) as r:
print(r.raster)
Output:
<osgeo.gdal.Dataset; proxy of <Swig Object of type 'GDALDatasetShadow *' at 0x04564728> >
Outside the with block the dataset is unreachable:
r.raster is None
Output:
True
There will be problems again if you bind another variable to r.raster so you might want to completely encapsulate it inside the Raster instance, along with any functionality you need. At this point you would be more or less reinventing Rasterio but if your needs are simple that might be better than depending on it.
As suggested in the comment, Rasterio via rasterio.open implements the behaviour you are looking for.
I made first folder for Class Movie:
import webbrowser
class Movie():
def __init__(self,movie_title,movie_storyline,poster_image,trailer_youtube):
self.title=movie_title
self.storyline=movie_storyline
self.poster_image_url=poster_image
self.trailer=trailer_youtube
def show_trailer(self):
webbrowser.open(self.trailer)
Then in another file, I am trying to call the function:
import media
toy_story= media.Movie("toy_story","a boy who have toys","http://www.imdb.com/title/tt0114709/mediaviewer/rm3813007616","http://www.imdb.com/videoplayer/vi2052129305?playlistId=tt0114709&ref_=tt_ov_vi")
avatar=media.Movie("Avatar","A marine on an alien planet","http://www.imdb.com/title/tt0499549/mediaviewer/rm843615744","http://www.imdb.com/title/tt0499549/videoplayer/vi531039513?ref_=tt_ov_vi")
avatar.show_trailer()
But, I am getting below error:
AttributeError: Movie instance has no attribute 'show_trailer'
Any suggesions?
I think your indentation is wrong for your class Movie. I cant reproduce the problem with the following 2 files in the same folder - perhaps your method is not correctly indented to be part of the class:
media.py
import webbrowser
class Movie():
def __init__(self,movie_title,movie_storyline,poster_image,trailer_youtube):
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer = trailer_youtube
def show_trailer(self):
print(self.trailer)
test.py
import media
toy_story=media.Movie("toy_story",
"a boy who have toys",
"http://www.imdb.com/title/tt0114709/mediaviewer/rm3813007616",
"http://www.imdb.com/videoplayer/vi2052129305?playlistId=tt0114709&ref_=tt_ov_vi")
avatar=media.Movie("Avatar",
"A marine on an alien planet",
"http://www.imdb.com/title/tt0499549/mediaviewer/rm843615744",
"http://www.imdb.com/title/tt0499549/videoplayer/vi531039513?ref_=tt_ov_vi")
avatar.show_trailer()
Output:
>> http://www.imdb.com/title/tt0499549/videoplayer/vi531039513?ref_=tt_ov_vi
>> Process finished with exit code 0
I have two Scripts. Script 1 is titled schemeDetails.The second script is a test script called temporaryFile that creates a schemeSetup object using the schemeSetup class which is within schemeDetails. Everything is hunky dory up to the point where I try to acess the method insertScheme which is within the schemeSetup Class.
I have imported the schemeDetails script using the following:
import schemeDetails
reload(schemeDetails)
from schemeDetails import *
I can create the schemeDetails Object and access its attributes
d = schemeDetails.schemeSetup() -- fine
print(d.scheme) -- fine
d.insertScheme() -- throws error
but trying to call the insertScheme function throws an error
I don't know why this is happening as the import statement looks above board to me. Any advice appreciated
from sikuli import *
import os
class schemeSetup(object):
#Uses default values
def __init__(
self,
scheme = "GM",
cardNumber = "1234567A",
month = "December",
year = "2015",
setSchemeAsDefault = True):
#Provide default values for parameters
self.scheme = scheme
self.cardNumber = cardNumber
self.month = month
self.year = year
self.setSchemeAsDefault = setSchemeAsDefault
#schemeDetails is not a sub
# class of patient. It is simply defined within the patient class
# - there is a huge difference.
#====================================================#
#schemeDetails Function
def insertScheme(self):
print("insertScheme Works")
#r = Regions()
#r.description("Patient Maintenance", "schemeDetails")
#myRegion = r.createRegion()
#myRegion.highlight(1)
#click(myRegion.find(insertSchemeButton))
#click(myRegion.find(blankSchemeEntry))
#type(self.scheme + Key.ENTER + Key.ENTER)
#type(self.cardNumber + Key.ENTER)
#type(self.month + Key.ENTER)
#type(self.year + Key.ENTER)
#type(" ")
#unticks HT link, HT linking should be in a separate function
#====================================================#
#schemeDetails Function
def editScheme(self):
print("editScheme Works")
#====================================================#
def deleteScheme(self):
pass
#====================================================#
It may be of importance that calling either of the bottom functions does not produce an error. If I put print("Hello") under editScheme, and call that method using s.editScheme the program compiles but I get no output. If I run print(s.editScheme) it returns None
Well it seems to be fixed now after changing the import format to this
import schemeDetails
from schemeDetails import schemeSetup
s = schemeDetails.schemeSetup()