[GRASS-dev] Python Scripting Library: mogrify command

Glynn Clements glynn at gclements.plus.com
Wed Jul 13 05:26:18 EDT 2011


Massimiliano Cannata wrote:

> I was wandering: does exist a python::core function capable to mogrigy 
> the inputs of a run_command()?
> 
> The mogrify function for psycopg2 is defined as follows:
> "/Return a query string after arguments binding. The string returned is 
> exactly the one that would be sent to the database running the execute() 
> method or similar./"
>  >>> cur.mogrify("INSERT INTO test (num, data) VALUES (%s, %s)", (42, 
> 'bar'))
> "INSERT INTO test (num, data) VALUES (42, E'bar')"
> 
> ...so for GRASS it could be:
>  >>> grass.mogrify_command("r.univar",flags="g",map="test")
> "r.univar -g map=test"

make_command() returns an argument list, e.g.:

	> import grass.script as grass
	> grass.make_command("r.univar",flags="g",map="test")
	['r.univar', '-g', 'map=test']

This is what all of the *_command() functions use to generate the
argument list.

Converting an argument list to a string is non-portable (/bin/sh has
significantly different syntax to cmd.exe) and quite tricky unless
you're willing to blindly quote everything to be on the safe side,
e.g. (for /bin/sh):

	args = [arg.replace("'", "'\\''") for arg in args]
	cmdstr = "'" + "' '".join(args) + "'"

It's much harder for Windows; see:

	http://msdn.microsoft.com/en-us/library/17w5ykft.aspx

or escape_arg() in lib/gis/spawn.c, or list2cmdline() in Python's
subprocess.py.

Note that none of the *_command() functions construct a command
string; they pass the argument list to subprocess.Popen() which
eventually either passes it to execve() (on Unix) or uses
list2cmdline() (on Windows).

-- 
Glynn Clements <glynn at gclements.plus.com>


More information about the grass-dev mailing list