Select to view content in your preferred language

Simple question about using variable in arcpy tools

968
5
11-12-2010 12:50 PM
SeanCook
Emerging Contributor
Hey all, I am trying to get the following script to work, and don't understand why it won't. Any help would be much appreciated. The first example won't run, the second executes normally, and I need to understand why. I am using the glob and os extensions to try to iterate through a bunch of files, but the tools doesn't seem to like variables.

example 1:

green = 'N:\\Bhutan\Spatial Data\\ASTER Images\\AST14DMO_V1.tif'
red = 'N:\\Bhutan\Spatial Data\\ASTER Images\\AST14DMO_V2.tif'
nir = 'N:\\Bhutan\Spatial Data\\ASTER Images\\AST14DMO_V3N.tif'
output = 'N:\\Bhutan\Spatial Data\\ASTER Images\\Stack1.img'
arcpy.CompositeBands_management(red;green;nir,output)

or: <arcpy.CompositeBands_management("red;green;nir","output")> Both ways fail.

example 2:

arcpy.CompositeBands_management("N:\\Bhutan\Spatial Data\\ASTER Images\\AST14DMO_V1.tif;N:\\Bhutan\Spatial Data\\ASTER Images\\AST14DMO_V2.tif;N:\\Bhutan\Spatial Data\\ASTER Imagesa\\AST14DMO_V3N.tif","N:\\Bhutan\Spatial Data\\ASTER Images\\Stack.img")
0 Kudos
5 Replies
SeanCook
Emerging Contributor
My error is:

Runtime error <class 'arcgisscripting.ExecuteError'>: ERROR 000271: Cannot open the input datasets Failed to execute (CompositeBands).
0 Kudos
DanPatterson_Retired
MVP Emeritus
outp ut)
in
arcpy.CompositeBands_management(red;green;nir,outp ut)

is that a typing or copying error?
0 Kudos
NiklasNorrthon
Frequent Contributor
red = 'file_red.tif'
# etc

"red;green;nir"

isn't using the contents of the variables red, green and nir, but the characters r, e, d, and so on, which is not what you want.

There are sevearal ways to join the contents from a number of strings into a new string. My personal favorit is the str.join method, which is very handy when you have your strings to join in a tuple or list:

my_strings = (red, green, nir) # first put them in a tuple
joined_strings = ';'.join(my_strings) # delimited by ;

Another possibility is to use string formatting:
joined_strings = '%s;%s;%s' % (red, green, nir)

And yet another way is to use string concatenation as ESRI do in most of their samples:
joined_strings = red + ';' + green + ';' + 'nir'

Personally I like the first two, and don't like last. I think concatenation makes the code hard to read.
0 Kudos
ChrisMathers
Deactivated User
Good to remember is that the string formatting method actually works well inside the tool parameters line.

arcpy.CompositeBands_management('%s,%s,%s' % (red,green,nir) ,output)

Oh and I agree Niklas, concatenation of strings especially if you have a lot of things you are joining, makes your code hard to read.
0 Kudos
SeanCook
Emerging Contributor
Thanks a bunch guys. Appreciate it!
0 Kudos