root / rdfalchemy / trunk / rdfalchemy / sparql / script.py

Revision 130, 2.3 kB (checked in by phil, 8 months ago)

fixes ticket:23 distinct class instances
Starts work on rdfsSubject with limited inferencing
begining of a paster command to build a .py from a schema

  • Property svn:executable set to *
Line 
1#!/usr/bin/env python
2# encoding: utf-8
3"""
4script.py
5
6Created by Philip Cooper on 2008-04-29.
7Copyright (c) 2008 Openvest.
8BSD License.
9"""
10from rdfalchemy.sparql import SPARQLGraph
11from rdfalchemy import __version__
12import sys
13import re
14import optparse
15
16
17usage = 'usage: sparql [options] [endpointURL] query_file'
18version = 'version: sparql '+__version__
19
20optparser = optparse.OptionParser(usage=usage, version=version)
21optparser.add_option('-q','--fin',help='Read query from file (defaults to stdin)')
22optparser.add_option('-o','--fout',help='output file name (defaluts to stdout)')
23optparser.add_option('-u','--url',help='url of the sparql endpoint')
24optparser.add_option('-t','--format',type='choice',choices=['xml','json','brtr'],help="format to return one of: ['xml','json','brtr']")
25optparser.set_defaults(format='xml')
26
27
28# time echo "select * { ?s a ?o } limit 2" | sparql -t xml -u $SPARQL1 - | xsltproc xml-to-html.xsl -
29class Usage(Exception):
30    def __init__(self, msg):
31        self.msg = msg
32
33
34def main(url=None):
35   
36    try:
37        output = ""
38       
39        try:
40            opts, args = optparser.parse_args()
41        except LookupError:
42            optparser.print_help()
43           
44
45        if len(args) < 1:
46            Usage('you must give at filename to read the query from..."-" signials stdin')
47        elif len(args) > 2:
48            Usage('too many args')
49       
50           
51        fname = args[-1]
52        if fname == '-':
53            stream = sys.stdin
54        else:
55            stream = file(fname)
56           
57        query = stream.read()
58       
59        #output = opt.get.fileOut or sys.stdout
60        if not opts.url:
61            try:
62                url =  re.search(r'(?:^|\n) *# *--url=([^ \s\n]+)',query).groups()[0]
63            except:
64                raise ValueError, "Need a url for the endpoint"
65        else: 
66            url = opts.url
67        if not opts.fout:
68            output = sys.stdout
69        else:
70            output = open(fout,"w")
71
72        result = SPARQLGraph(url).query(query,resultMethod = opts.format ,rawResults=True)
73        print >>output, result.read()
74
75           
76   
77    except Usage, err:
78        print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg)
79        print >> sys.stderr, "\t for help use --help"
80        return 2
81
82
83if __name__ == "__main__":
84    sys.exit(main())
Note: See TracBrowser for help on using the browser.