Package rdfalchemy :: Package sparql :: Module script
[hide private]
[frames] | no frames]

Source Code for Module rdfalchemy.sparql.script

 1  #!/usr/bin/env python 
 2  # encoding: utf-8 
 3  """ 
 4  script.py 
 5   
 6  Created by Philip Cooper on 2008-04-29. 
 7  Copyright (c) 2008 Openvest.  
 8  BSD License. 
 9  """ 
10  from rdfalchemy.sparql import SPARQLGraph 
11  from rdfalchemy import __version__ 
12  import sys 
13  import re 
14  import optparse 
15   
16   
17  usage = 'usage: sparql [options] [endpointURL] query_file' 
18  version = 'version: sparql '+__version__ 
19   
20  optparser = optparse.OptionParser(usage=usage, version=version) 
21  optparser.add_option('-q','--fin',help='Read query from file (defaults to stdin)') 
22  optparser.add_option('-o','--fout',help='output file name (defaluts to stdout)') 
23  optparser.add_option('-u','--url',help='url of the sparql endpoint') 
24  optparser.add_option('-t','--format',type='choice',choices=['xml','json','brtr'],help="format to return one of: ['xml','json','brtr']") 
25  optparser.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 - 
29 -class Usage(Exception):
30 - def __init__(self, msg):
31 self.msg = msg
32 33
34 -def 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 83 if __name__ == "__main__": 84 sys.exit(main()) 85