[GRASS-user] retrieving a GRASS-python script return values

Glynn Clements glynn at gclements.plus.com
Thu Feb 24 00:54:12 EST 2011

katrin eggert wrote:

> I'm trying to parse a list of strings like this:
>        sys.stdout.write(output_v)
> And I get this error
> TypeError: argument 1 must be string or read-only character
> buffer, not list

The simplest way to write Python objects is to use repr(), which will
convert them to a string in the format which Python uses for literals.

	> x=[1,2,3]
	> repr(x)
	'[1, 2, 3]'
	> sys.stdout.write(repr(x))
	[1, 2, 3]> 

You can then parse the value with eval(). This will work for any
primitive type (anything which has a literal syntax (numbers, strings,
lists, tuples, dictionaries) as well as sets, but not for arbitrary

Alternatively, for lists you can use the .join and and .split methods
(along with e.g. str() and int() to convert the members to/from
strings), e.g.:

	> x=[1,2,3]
	> map(str,x)
	['1', '2', '3']
	> y=','.join(map(str,x))
	> y
	> y.split(',')
	['1', '2', '3']
	> map(int,y.split(','))
	[1, 2, 3]

For passing more complex data between processes, look at the "pickle"
module from Python's standard library. This can handle arbitrary
objects, and handles references correctly (i.e. multiple references to
the same object won't get converted into multiple, distinct objects).

Glynn Clements <glynn at gclements.plus.com>

More information about the grass-user mailing list