0

I have created a module to prepare an XML file. Since xml.etree does not output a pretty XML I use dom.

****Module:****
    from xml.etree import ElementTree
    from xml.dom import minidom
    import gc

 def prettify(elem):
        """Return a pretty-printed XML string for the Element.
        """
        rough_string = ElementTree.tostring(elem,"utf-8")
        reparsed = minidom.parseString(rough_string)
        tempString = str(reparsed.toprettyxml(indent="  "))
        reparsed = None
        return tempString

import xml.etree.ElementTree as ET

try:    
    class source():
        def __init__(self):
            self.top=ET.Element("nrml",{"xmlns:gml":"http://www.opengis.net/gml","xmlns":"http://openquake.org/xmlns/nrml/0.4"})
            self.subtop=ET.SubElement(self.top,"sourceModel")
        def clean(self):
            self.top=None
            self.subtop=None

    class simpleFaultSource():
        sourceInstance = source()

        def __init__(self, **kwargs):
            for k, v in kwargs.items():
                setattr(self, k, v)
            self.simpleFaultSourceAttributes={} 
            self.simpleFaultSourceAttributes["id"]= self.id
            self.simpleFaultSourceAttributes["name"]=self.name
            self.simpleFaultSourceAttributes["tectonicRegion"]="ActiveShallowCrust"
            projectName = self.filename 
            simpleFaultSource.sourceInstance.subtop.set("name", projectName+":"+self.layername )
            self.createTags()
            self.addText(**kwargs)

        def createTags(self):
            self.simpleFaultSource= ET.SubElement(simpleFaultSource.sourceInstance.subtop, \
      "simpleFaultSource",self.simpleFaultSourceAttributes)

    except Exception as e:
        print("Printing at module!")    
        print(e.message)
        print(e.__class__.__name__)
    finally:
        gc.collect()

Once I execute the main file once, the output file is correct.

****Main:****
from qgis.core import *
from PyQt4.QtCore import *
import processing
from qgis.utils import iface


import getpass
username = getpass.getuser()
import sys
exePath=r'C:\Users\10011\Desktop\Control\qgis\02_JG_Summit\02_scripts'
sys.path.append(exePath)
import oq_classes

try:

    layer = iface.activeLayer()
    #layer = processing.getObject(input_layer)
    featureList=[]
    prjPath=QgsProject.instance().fileName()
    splitPath=prjPath.split("/")
    filename=splitPath[-1]
    path="/".join(splitPath[:-2])
    savePath=path+"/05_output/"

    if layer.geometryType() == QGis.Line:
            layerType = 1
            LT = "Line"
        for f in layer.getFeatures():
            g = f.geometry()
            l = g.asPolyline()
            temp=""

            for e in l:
                temp = temp + "\n"+str(e[0])+" "+str(e[1])
            temp=temp+"\n"
            kwargs={"name": f['name'], "id" : f['id'], "pos" : temp,"layername":layer.name(),"filename":filename}
            tempInstance=oq_classes.simpleFaultSource(**kwargs)
            featureList.append(tempInstance)
        newPath=savePath+oq_classes.simpleFaultSource.__name__+".xml"
        string1=oq_classes.prettify(oq_classes.simpleFaultSource.sourceInstance.top)

        with open(newPath,"w") as f:
            f.write(string1)
except Exception as e :
    print(e.message)
    print(e.__class__.__name__)

finally:
    gc.collect()

Every time I run the script again, the children node (simpleFaultSource) gets duplicated under the parent node (sourceModel) unless I close QGis and open it again. Summarized output is shown below, everything below the red line is duplicated within the same parent node when executing the script again .

enter image description here

My understanding is that the import, classes and instances should not be in memory after the script has finished execution. Is this an issues with my implementation, Python or with QGis (version 2.14)?

  • 1
    That's a lot of code, intermingled with debugging prints etc. Please make it as minimal as possible to read and reproduce the issue. This saves time and effort for everyone. – bugmenot123 Dec 21 '17 at 9:30
  • 1
    Just give me a moment – Stephen Jacob Dec 21 '17 at 9:42
  • You're mixing classes and instances of classes and class attributes and instance attributes. The class attributes will be held in memory by the interpreter (qgis python) – user2856 Jan 7 '18 at 20:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.