31 from __future__
import print_function
32 from optparse
import OptionParser
39 sys.stderr.write(
"LOG - " +
str(msg) +
"\n")
43 prs = OptionParser(version=
"%prog",
44 usage=
"%prog -d <DB> -r <RASTER> -o <FILE> [-f <FORMAT>] [-c <OPTIONS>]",
45 description=
"Output raster in a GDAL raster format")
46 prs.add_option(
"-d",
"--db", dest=
"db", action=
"store", default=
None,
47 help=
"PostgreSQL database connection string, required")
48 prs.add_option(
"-r",
"--raster", dest=
"raster", action=
"store", default=
None,
49 help=
"sql expression to create or access a existing raster, required")
50 prs.add_option(
"-o",
"--output", dest=
"output", action=
"store", default=
None,
51 help=
"file to put the output of ST_AsGDALRaster if successful, required")
52 prs.add_option(
"-f",
"--format", dest=
"format", action=
"store", default=
"GTiff",
53 help=
"format of GDAL raster output, optional, default=GTiff")
54 prs.add_option(
"-c",
"--config", dest=
"config", action=
"store", default=
None,
55 help=
"comma separated list of GDAL raster creation options, optional")
56 prs.add_option(
"-v",
"--verbose", dest=
"verbose", action=
"store_true", default=
False,
57 help=
"be excessively verbose and useful for debugging")
59 (opts, args) = prs.parse_args()
62 prs.error(
"use -d option to specify database connection string")
63 if opts.raster
is None:
64 prs.error(
"use -r option to specify a sql expression for a raster")
65 if opts.output
is None:
66 prs.error(
"use -o option to specify raster output file")
68 if opts.config
is not None:
69 opts.cfg = opts.config.split(
',')
74 VERBOSE = opts.verbose
76 conn = psycopg2.connect(opts.db)
77 logit(
"Connected to %s" % opts.db)
78 logit(
"Raster expression is %s" % opts.raster)
81 sql =
"SELECT ST_AsGDALRaster(%s, %%s, %%s::text[], NULL::integer)" % (opts.raster)
82 cur.execute(sql, (opts.format, opts.cfg))
83 logit(
"Number of rows: %i" % cur.rowcount)
84 rec = cur.fetchone()[0];
85 logit(
"size of raster (bytes): %i" % len(rec))
87 fh = open(opts.output,
'wb', -1)
91 logit(
"size of %s (bytes): %i" % (opts.output, os.stat(opts.output)[6]));
96 print(
"raster outputted to %s" % opts.output);
98 except Exception
as e: