Reputation: 96
I'm parsing xml data and when i print the variable inside the condition but when i call that same variable later is not defined. Why does this happen
Here the variable "LaunchPath works fine:
import xml.sax
class PathHandler( xml.sax.ContentHandler ):
def __init__(self):
self.CurrentData = ""
# Call when an element starts
def startElement(self, tag, attributes):
self.CurrentData = tag
if tag == "application":
LaunchApp = attributes["android:name"].replace(".", "/")
LaunchPath = LaunchApp + ".smali"
print LaunchPath
if ( __name__ == "__main__"):
# create an XMLReader
parser = xml.sax.make_parser()
# turn off namepsaces
parser.setFeature(xml.sax.handler.feature_namespaces, 0)
# override the default ContextHandler
Handler = PathHandler()
parser.setContentHandler( Handler )
parser.parse("AndroidManifest.xml")
But when i attempt to print "LaunchPath" at the bottom like this it doesn work:
import xml.sax
class PathHandler( xml.sax.ContentHandler ):
def __init__(self):
self.CurrentData = ""
# Call when an element starts
def startElement(self, tag, attributes):
self.CurrentData = tag
if tag == "application":
LaunchApp = attributes["android:name"].replace(".", "/")
LaunchPath = LaunchApp + ".smali"
if ( __name__ == "__main__"):
# create an XMLReader
parser = xml.sax.make_parser()
# turn off namepsaces
parser.setFeature(xml.sax.handler.feature_namespaces, 0)
# override the default ContextHandler
Handler = PathHandler()
parser.setContentHandler( Handler )
parser.parse("AndroidManifest.xml")
print LaunchPath
This gives me an error that "LaunchPath" is undefined.
Why does this happen and how can i fix it.
Upvotes: 0
Views: 44
Reputation: 1169
That is because LaunchPath
is a local variable and you are trying to reference it out of its scope.
Upvotes: 0
Reputation: 1049
This is because your variable LaunchPath is defined inside the scope of the function startElement
, since you declared it there when the functions returns it also "erases" the variable.
You should read about python scopes
Upvotes: 3