-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathknow-sparql-save
executable file
·46 lines (37 loc) · 2.08 KB
/
know-sparql-save
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/python3
import sys
import os
import urllib
import argparse
from rdflib import Graph, URIRef
from PKB4Unix import endpoint, iotools
argparser = argparse.ArgumentParser(description='Save a graph from a SPARQL endpoint to a file')
argparser.add_argument('identifiers', nargs='+', metavar='URI',
help=('Graphs to save'))
argparser.add_argument('-f', '--file', nargs='+', metavar='FILE', dest='files',
help='Override file name. - denotes STDOUT. If used, the number of identifiers must match the number of identifier arguments.')
argparser.add_argument('-t', '--content-type', nargs='+', dest='contentTypes', metavar='TYPE',
help=('Set content-type to be used in the Accept-header of the SPARQL request. '
'For writing to STDOUT, it defaults to DEFAULT_FROMAT. If used, the number of content-types must be one or match the number of identifier arguments.'))
args = argparser.parse_args()
args.identifiers = [iotools.absurl(ident) for ident in args.identifiers]
if args.files and not (len(args.files) == len(args.identifiers)):
print("--file must have as many arguments as there are graphs to save")
elif not args.files:
args.files = [iotools.url2localpath(ident) for ident in args.identifiers]
if args.contentTypes and not (len(args.contentTypes) == len(args.identifiers)):
if len(args.contentTypes) == 1:
args.contentTypes *= len(args.identifiers)
else:
print("--content-type must have one or as many arguments as there are graphs to save")
elif not args.contentTypes:
args.contentTypes = [DEFAULT_FORMAT if ident=='-' else iotools.guess_contentType(ident) for ident in args.files]
for (filename, uri, contentType) in zip(args.files, args.identifiers, args.contentTypes):
print("Saving {} to {} ...".format(uri, "STDOUT" if filename == '-' else filename))
if filename == '-':
f = sys.stdout.buffer
else:
f = open(filename, mode="bw")
with endpoint.get_data(uri, contentType) as response:
for s in iter(lambda: response.read(4096), b''):
f.write(s)