def main(argv=[__name__]): #Ideas borrowed from # http://www.artima.com/forums/flat.jsp?forum=106&thread=4829 if argv is None: argv = sys.argv try: try: optparser = command_line(argv) dtll_fname = ARGS[1] except KeyboardInterrupt: pass except: raise Usage(optparser.format_help()) enc, dec, inwrap, outwrap = codecs.lookup('utf-8') output_stem = OPTIONS.dt_modname_stem if not output_stem: output_stem = os.path.splitext(dtll_fname)[0] + '-datatypes' if dtll_fname == '-': dtllf = sys.stdin else: dtllf = open(dtll_fname, 'r') dtll_doc = NonvalidatingReader.parseStream(dtllf, 'http://example.com') run(dtll_doc, output_stem, OPTIONS.test_ready) except Usage, err: print >>sys.stderr, err.msg return 2
def main(argv=[__name__]): #Ideas borrowed from # http://www.artima.com/forums/flat.jsp?forum=106&thread=4829 if argv is None: argv = sys.argv try: try: optparser = command_line(argv) dtll_fname = ARGS[1] except KeyboardInterrupt: pass except: raise Usage(optparser.format_help()) enc, dec, inwrap, outwrap = codecs.lookup('utf-8') output_stem = OPTIONS.dt_modname_stem if not output_stem: output_stem = os.path.splitext(dtll_fname)[0] + '-datatypes' if dtll_fname == '-': dtllf = sys.stdin else: dtllf = open(dtll_fname, 'r') dtll_doc = NonvalidatingReader.parseStream(dtllf, 'http://example.com') run(dtll_doc, output_stem, OPTIONS.test_ready) except Usage, err: print >> sys.stderr, err.msg return 2
def parseFile(file): """File can be an open handle or filesystem path""" from Ft.Xml.Domlette import NonvalidatingReader if isinstance(file, basestring): dom = NonvalidatingReader.parseUri("file:%s" % self._file) else: dom = NonvalidatingReader.parseStream(file, **kwargs) return McmLogFile(dom)
def _convertXML(self): """ Convert an XML result into a Python dom tree. This method can be overwritten in a subclass for a different conversion method. :return: converted result :rtype: 4Suite DOMlette instance (http://infinitesque.net/projects/4Suite/docs/CoreManual.html#domlette_API) """ try: from Ft.Xml import InputSource from Ft.Xml.Domlette import NonvalidatingReader except ImportError: raise Exception("4Suite-XML needs to be installed (http://pypi.python.org/pypi/4Suite-XML/1.0.2)") return NonvalidatingReader.parseStream(self.response, MEANINGLESS_URI)
def Parse(source): """ Convenience function for parsing XML. Use this function with a single argument, which must either be a string (not Unicode object), file-like object (stream), file path or URI. Returns a Domlette node. Only pass strings or streams to this function if the XML is self-contained XML (i.e. not requiring access to any other resource such as external entities or includes). If you get URI resolution errors, do not use this function: use the lower-level APIs instead. As an example, if you want such resolution to use the current working directory as a base, parse as follows for strings: from Ft.Xml.Domlette import NonvalidatingReader from Ft.Lib import Uri XML = "<!DOCTYPE a [ <!ENTITY b "b.xml"> ]><a>&b;</a>" base = Uri.OsPathToUri('') #Turn CWD into a file: URL doc = NonvalidatingReader.parseString(XML, base) # during parsing, the replacement text for &b; # will be obtained from b.xml in the CWD For streams, use "parseStream" rather than "parseString" in the above. """ #do the imports within the function: a tad bit less efficient, but #avoid circular crap from Ft.Xml.Domlette import NonvalidatingReader from Ft.Lib import Uri, Uuid from Ft.Xml.Lib.XmlString import IsXml if hasattr(source, 'read'): #Create dummy Uri to use as base dummy_uri = 'urn:uuid:' + Uuid.UuidAsString(Uuid.GenerateUuid()) return NonvalidatingReader.parseStream(source, dummy_uri) elif IsXml(source): dummy_uri = 'urn:uuid:' + Uuid.UuidAsString(Uuid.GenerateUuid()) return NonvalidatingReader.parseString(source, dummy_uri) elif Uri.IsAbsolute(source): #or not os.path.isfile(source): return NonvalidatingReader.parseUri(source) else: return NonvalidatingReader.parseUri(Uri.OsPathToUri(source))
def contexts(self, triple=None): """ iterates over results to SELECT ?NAME { GRAPH ?NAME { ?s ?p ?o } } returning instances of this store with the SPARQL wrapper object updated via addNamedGraph(?NAME) This causes a named-graph-uri key / value pair to be sent over the protocol """ raise NotImplementedError(".contexts(..) not supported") self.setQuery("SELECT ?NAME { GRAPH ?NAME { ?s ?p ?o } }") doc = NonvalidatingReader.parseStream(self.query().convert) for result in doc.xpath('/sparql:sparql/sparql:results/sparql:result', explicitNss=sparqlNsBindings): statmentTerms = {} for binding in result.xpath('sparql:binding', explicitNss=sparqlNsBindings): term = CastToTerm(binding.xpath('*')[0]) newStore = SPARQLStore(self.baseURI) newStore.addNamedGraph(term) yield Graph(self,term)
def svn_log(self): """ Make a log query to the Subversion repository, return parsed XML document of query output. """ # Calculate the start and end times for log query now = time.time() then = now - self.LOG_PERIOD # Format the start/end times for use in svn command start_time = time.strftime("%Y-%m-%d", time.localtime(then)) end_time = time.strftime("%Y-%m-%d", time.localtime(now)) # Build the svn command invocation, execute it, and return # the XML results in a parsed document. cmd = '%s log --xml -v -r "{%s}:{%s}" %s' % \ (self.SVN_BIN, start_time, end_time, self.url) (sout, sin) = popen4(cmd) return NonvalidatingReader.parseStream(sout, self.url)
else: selectVars.append(predVar) if obj is not None: termsSlots[objVar] = obj else: selectVars.append(objVar) query ="SELECT %s WHERE { %s %s %s }"%( ' '.join([term.n3() for term in selectVars]), termsSlots.get(subjVar, subjVar).n3(), termsSlots.get(predVar, predVar).n3(), termsSlots.get(objVar , objVar ).n3() ) self.setQuery(query) doc = NonvalidatingReader.parseStream(self.query().response) for rt,vars in TraverseSPARQLResultDOM(doc,asDictionary=True): yield (rt.get(subjVar,subject), rt.get(predVar,predicate), rt.get(objVar,obj)),None def triples_choices(self, (subject, predicate, object_),context=None): """ A variant of triples that can take a list of terms instead of a single term in any slot. Stores can implement this to optimize the response time from the import default 'fallback' implementation, which will iterate over each term in the list and dispatch to tripless """ raise NotImplementedError('Triples choices currently not supported') def __len__(self, context=None):