本文整理汇总了Python中xml.sax.parseString函数的典型用法代码示例。如果您正苦于以下问题:Python parseString函数的具体用法?Python parseString怎么用?Python parseString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了parseString函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: process
def process(self, wealth, imported_file, account=None):
gzip_file = GzipFile(fileobj=imported_file.file)
decompressed = gzip_file.read()
parser = make_parser()
model = {
'accounts': {},
'categories': {},
'currency': [],
'transactions': [],
'category_splits': [],
'account_splits': [],
'wealth': wealth }
handler = KMYXmlHandler(model)
parser.setContentHandler(handler)
parseString(decompressed, handler)
accounts = model['accounts']
categories = self.__build_category_tree(model['categories'])
transactions = model['transactions']
account_splits = model['account_splits']
category_splits = model['category_splits']
# if main currencies differ, re-calculate
if model['currency'] != model['wealth'].currency:
exchange_rate = get_rate(model['currency'], model['wealth'].currency)
for split in category_splits:
split.amount *= exchange_rate
self.accounts = accounts.values()
self.categories = categories.values()
self.transactions = [transaction for transaction in transactions if transaction.date]
self.category_splits = [split for split in category_splits if split.category ]
self.account_splits = [split for split in account_splits if split.account ]
self.currency = model['currency']
示例2: checkStatus
def checkStatus(seHost):
# Check if the node is in status downtime
cmdString = CURL_CMD + "\"" + GOCDB_DOWNTIME_URL + seHost + "\""
if DEBUG: print "Command: " + cmdString
status, output = commands.getstatusoutput(cmdString)
if DEBUG: print "Response: " + output
if status <> 0:
print "Error when querying the GOCDB for downtimes: " + output
else:
parseString(output, SaxDowntimeHandle())
# Check if the node is in status "not in production" or "not monitored"
cmdString = CURL_CMD + "\"" + GOCDB_SERVICE_URL + seHost + "\""
if DEBUG: print "Command: " + cmdString
status, output = commands.getstatusoutput(cmdString)
if DEBUG: print "Response: " + output
if status <> 0:
print "Error when querying the GOCDB for service status: " + output
else:
parseString(output, SaxServiceHandle())
# Display the node status
if len(serviceStatus) <> 0:
if PRETTY: sys.stdout.write(" %-8s%-48s" % (service, seHost))
else: sys.stdout.write(service + "|" + seHost + "|")
isFirst = True
for status in serviceStatus:
if isFirst: sys.stdout.write(status)
else: sys.stdout.write(", " + status)
isFirst = False
print
示例3: __init__
def __init__(self, msw):
"""
A list of objects in the iServer database.
The msw argument can either be a string containing the XML
contents of the database or a session object. If a session is
passed, it will be used to get the database.
Each type is a callable object (for use in XML parser
dispatching) and has an associated long name and a more
convenient short name for use in test scripts. Beware of the
short names when using 'from iserver import *' - they are
common and could collide with test script objects. First
character is capitalized.
"""
if type(msw) is ListType:
# A text stream created by file.readlines()
self.rawXml = string.join(msw)
else:
self.msw = msw
self._getDatabaseFromMSW()
parser = sax.make_parser()
handler = IServerHandler()
sax.parseString(self.rawXml, handler)
for i in handler.objList:
self.append(i)
示例4: fetch_index
def fetch_index():
"""Return an iterable of every project name on PyPI."""
r = requests.get('https://pypi.python.org/simple/')
sax_handler = PyPIIndexHandler()
sax.parseString(r.text, sax_handler)
return sax_handler.projects
示例5: test_case1
def test_case1(self):
str1= bytes(
'<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
'<root>\r\n'
' <value1>5</value1>\r\n'
' <value2>1.23</value2>\n'
' <section first="1" second="long string">\n'
' <value3>on</value3>\n'
' <value4>1</value4>\n'
' <value4>2</value4>\n'
' <value4>42</value4>\n'
' </section>\n'
'</root>'.encode("utf-8") )
result= str(
'<?xml version="1.0" encoding="utf-8"?>\n'
'<root>\n'
' <value1>5</value1>\n'
' <value2>1.23</value2>\n'
' <section first="1" second="long string">\n'
' <value3>on</value3>\n'
' <value4>1</value4>\n'
' <value4>2</value4>\n'
' <value4>42</value4>\n'
' </section>\n'
'</root>\n' )
parseString(str1, XmlReader(self.handler1))
#print( self.stdout.getvalue() )
self.assertEqual(result, self.stdout.getvalue() )
示例6: read_applexml_string
def read_applexml_string(data, sql_filename):
'''Parses the data as Apple XML format. Returns the top node.'''
#parser = sax.make_parser()
handler = AppleXMLHandler()
#parser.setContentHandler(handler)
#parser.setEntityResolver(AppleXMLResolver())
sax.parseString(data, handler)
album_xml = handler.gettopnode()
if sql_filename:
# keywords are no longer available in XML
# quick hack to pull them out of the sqlite database instead
conn = sqlite3.connect(sql_filename)
c = conn.cursor()
photos = album_xml['Master Image List']
for key in photos:
photo = photos[key]
if 'Keywords' not in photo:
photo['Keywords'] = []
c.execute('select keywordId from RKKeywordForVersion where versionId is ?', (key,))
for keyword in c.fetchall():
if keyword:
photo['Keywords'].append(keyword[0])
album_xml['List of Keywords'] = {}
c.execute('select modelId, name from RKKeyword')
for keyword in c.fetchall():
album_xml['List of Keywords'][keyword[0]] = keyword[1]
return album_xml
示例7: __init__
def __init__(self, uri):
self.uri = uri
self.xml = download_http_content(uri)
self.handler = None
self._capabilities = []
self.uriHandler = UriGadgetHandler ()
parseString(self.xml, self.uriHandler)
示例8: check
def check(self, dialog_on_none=False):
"""
This function should be called whenever a version test is desired
(eg. in the mainloop on a timer). If a dialog is requested, set
dialog_on_none.
"""
data = self.__get_update_file()
if data:
print data
sax.parseString(data, self)
for type in ["major", "minor"]:
available, version = self.__new_version_available[type]
if available:
if self.__remind_again[type]:
dialog.info(_("A version update is available"),
_("You are running version %(version)s.\n\n"
"Version %(newer_version)s is available "
"at %(URL)s.") %
{"version": VERSION,
"newer_version": self.__format_version(version),
"URL": dialog.urlwrap("http://www.gdesklets.de")},
(_("_Stop reminding me"), lambda t=type: self.__remind(t, False)),
(_("_Remind me again"), None))
elif dialog_on_none:
dialog.info(_("No version updates available"),
_("You are running the latest version (%(version)s).") %
{"version": VERSION})
break
# Run again next timer expiration
return True
示例9: xml2yaml
def xml2yaml(fname):
handler = XMLNodeHandler()
parseString(caffeine_cml,handler)
PrintVisitor(handler.getroot())
#YAMLPrintVisitor(handler.getroot())
#print PythonObjectVisitor(handler.getroot())
return
示例10: get_ping_urls
def get_ping_urls(url):
"""
returns a two-tuple of lists, ([pingback urls],[trackback urls])
"""
ping_urls = []
tb_urls = []
txt = urllib.urlopen(url).read()
print "Got %d bytes" % len(txt)
soup = bs(txt)
# walk through the links, looking for ping-entries
for a in soup.findAll('link'):
print a
rel = a.get('rel')
if rel == 'pingback':
print "Got pingback URL:", a.href
ping_urls.append(a.get('href'))
# now do t he trackbacks...
tb_re=re.compile('(<rdf:RDF .*?</rdf:RDF>)')
rdfdata = RDF()
for x in tb_re.findall(txt.replace('\n',' ')):
parseString(x, rdfdata)
# print rdf.ids
print "URL:", rdfdata.attrs.get('dc:identifier')
print "Trackback URL:", rdfdata.attrs.get('trackback:ping')
tb_urls.append(rdfdata.attrs.get('trackback:ping'))
return ping_urls, tb_urls
示例11: test_case1
def test_case1(self):
str1= bytes(
'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n'
'<root>\r\n'
' <value1>5</value1>\r\n'
' <value2>1.23</value2>\n'
' <section>\n'
' <value3>on</value3>\n'
' <value4>1</value4>\n'
' <value4>2</value4>\n'
' <value4>42</value4>\n'
' </section>\n'
'</root>'.encode("utf-8") )
parseString(str1, XmlReader(self.handler1))
# except Exception as ex:
# print("In Line {0}:{1}:\n{2}".format(handler._parent.locator.getLineNumber(),
# handler._parent.locator.getColumnNumber(),
# ex))
self.assertEqual(self.val1, 5)
self.assertEqual(self.val2, 1.23)
self.assertEqual(self.val3, True)
self.assertEqual(self.val4, [1,2,42])
self.assertEqual(self.stderr.getvalue(), "")
self.assertEqual(self.stdout.getvalue(), "")
示例12: test_process_guid_feed
def test_process_guid_feed(self):
p = FakeItemProcessor();
handler = RssHandler(p)
parseString(guid_rss, handler)
self.assertEqual(2, p.process_calls)
self.assertEqual(p.last_guid, 'http://example/b')
self.assertEqual(p.last_url, 'http://example/?page=download&tid=413995')
示例13: do_build
def do_build(self, source, fromFile, catalog=None, bagcls=Bag, empty=None, testmode=False):
"""TODO
:param source: TODO
:param fromFile: TODO
:param catalog: TODO
:param bagcls: TODO
:param empty: TODO
:param testmode: TODO"""
if not testmode:
bagImport = _SaxImporter()
else:
bagImport = sax.handler.ContentHandler()
if not catalog:
catalog = gnrclasses.GnrClassCatalog()
bagImport.catalog = catalog
bagImport.bagcls = bagcls
bagImport.empty = empty
bagImportError = _SaxImporterError()
if fromFile:
infile = open(source)
source = infile.read()
infile.close()
if isinstance(source, unicode):
if source.startswith('<?xml'):
source = source[source.index('?>'):]
source = "<?xml version='1.0' encoding='UTF-8'?>%s" % source.encode('UTF-8')
source = re.sub("&(?!([a-zA-Z][a-zA-Z0-9]*|#\d+);)", "&", source)
sax.parseString(source, bagImport)
if not testmode:
result = bagImport.bags[0][0]
if bagImport.format == 'GenRoBag': result = result['GenRoBag']
if result == None: result = []
return result
示例14: parseInfo
def parseInfo(self):
infoXml = self.checkOutput((self.svnCmd, "info", "--xml")) # bytes in python 3.
infoHandler = SvnInfoHandler()
sax.parseString(infoXml, infoHandler)
self.uuid = infoHandler.uuid
self.url = infoHandler.url
self.lastChangeRev = infoHandler.getLastChangeRevision()
示例15: run_instances
def run_instances(self, image_id, instance_type_id, blocks = None, instance_count = -1, subnet_id = "",
private_ip_address = "", security_group_ids = None, key_name = ""):
"""
Launch specified number of instances in your
account.
param args: Arguments passed to the function
The function expects following arguments -
1. image id
2. instance type id
3. subnet id (optional)
4. security group id (optional)
5. key name (optional, but needed to access machine)
6. instance count (optional)
7. private ip address (optional)
8. block device mapping (optional)
"""
response = instance.run_instances(self.url, self.verb, self.headers,
self.version, image_id, instance_type_id, blocks, instance_count, subnet_id, private_ip_address, security_group_ids, key_name)
if response is not None :
res = RunInstancesResponse.RunInstancesResponse()
print response.text
parseString(str(response.text), res)
return res
else :
return None