|
POST
|
Even though I set: arcpy.env.qualifiedFieldNames = False and verify with a print statement that qualifiedFieldNames is "False", when I join a layer file to a table, the field names still have the predicated file/table name preceding it. I believe the qualified field names still exist in the table view after you do a join; the environment setting comes into play when that table view is accessed by a tool that copies the table, for example, CopyFeatures_management. In the tool output, the names should not be qualified if qualifiedFieldNames is False. This is what is demonstrated in the example in the help for qualifiedFieldNames.
... View more
11-14-2012
09:40 AM
|
0
|
0
|
1824
|
|
POST
|
curious as to what´s bugged/why my code doesn´t work for you. Rafael, your code has two problems I should have pointed out directly. These are both things that have tripped me up so I think they are worth sharing with the list. 1. You used of the "in" operator instead of "==" to compare strings. This could give you unexpected results because "ras_test2" in l would give a true for elements "ras_test2","ras_test22.asc", and "ras_test2_2". 2. This one has bit me before, and I missed it again in the code above. You should not modify a list while you are looping over it. Rhett probably has run into it, which is why he wisely makes a new list. (Note this is not an issue with the list comprehension because it is creating a new list, not modifying an existing one.) An easy way to avoid the problem is to make a copy using list():
for l in list(ld):
if l == "contour": ld.remove(l)
... View more
11-14-2012
06:25 AM
|
0
|
0
|
2468
|
|
POST
|
Since I have written the code to convert the rasters to raster layers for the "slice" operation, it seems clumsy to repeat that conversion on the output of "slice" in order to then use the "apply symbology" process. Is it possible in coding "slice" to create a layer as the output right away? Or is there a better way? Just to reiterate - it is not a conversion - a layer is an object that points to the dataset. Creating a raster layer only takes a moment to do. Most raster tools accept either raster layers or rasters as input. I'm assuming you're writing a script tool - if the output is your sliced raster, you don't need to do this in code. Just set up your output raster as an output parameter, and set that parameters output Symbology property to point to your .lyr file. Make sure your slice output is saved to that output parameter path.
... View more
11-13-2012
02:18 PM
|
0
|
0
|
877
|
|
POST
|
Unfortunately, I believe there were bugs in Rafael's code. These should work:
dsets = arcpy.ListDatasets("*","Feature")
if "contour" in dsets:
dsets.remove("contour")
The list comprehension version is kind of tricky to read, but it works too: dsets = [ds for ds in arcpy.ListDatasets("*","Feature") if ds != "contour"]
... View more
11-13-2012
02:01 PM
|
0
|
0
|
2468
|
|
POST
|
>>> arcpy.Buffer_analysis(r'C:\avhome\Data\QLDgeology\LassitersReef_FileBased.gdb\WongaExt','test2','2 kilometers')
Runtime error Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\program files (x86)\arcgis\desktop10.1\arcpy\arcpy\analysis.py", line 686, in Buffer raise e ExecuteError: ERROR 000210: Cannot create output ..\..\Users\Graeme\Documents\ArcGIS\Default.gdb\test2 Failed to execute (Buffer).
>>> This is interesting. I'm wondering if these relative paths for your output workspace are causing a problem for background processing, as the background process may not be as smart about knowing where the current folder is? Where is your map document located? Is it in your Documents folder?
... View more
11-13-2012
01:05 PM
|
0
|
0
|
1386
|
|
POST
|
Have you run into this issue before using this package? Or do I need to contact USGS to figure it out? Uh, that would be me. Suggestions: 1) Set your geoprocessing scratch and current workspace to a folder. It looks like you have let it default, which is breaking the tool. 2) As the help I wrote for the tool suggests, something to try is to run the Feature Weights To Table and Tabulate Weight Table tools separately.
... View more
11-13-2012
11:31 AM
|
0
|
0
|
1836
|
|
POST
|
Now I get the following problem when I run the script: Traceback (most recent call last):
File "W:\Organisation\10013 Aktualisierung der Luftbilddatenbank in Bezug auf Georeferenzierung\Daten\georeference_in_attribute_table_new.py", line 31, in <module>
row.top = arcpy.GetRasterProperties_management(raster, "top")
File "C:\Program Files (x86)\ArcGIS\Desktop10.0\arcpy\arcpy\arcobjects\_base.py", line 35, in __setattr__
return setattr(self._arc_object, attr, ao)
ValueError: Row: Invalid input value for setting GetRasterProperties returns a result object. See the [post=238595]top of this thread[/post] for how to convert that into a value you can write to a field.
... View more
11-09-2012
08:37 AM
|
0
|
0
|
2006
|
|
POST
|
I ran into the same problem when using python to add hyperlinks. As hyperlinks contain "\" characters it sometimes happened that a "\n" was in the hyperlink. I solved it by passing in the hyperlink as a raw string instead of a normal string: hyperlink = "c:\somehyperlink\name_of_file"
arcpy.CalculateField_management(TableToEdit, "HYPERLINK_FIELD", r"r'" + hyperlink + r"'", "PYTHON") The above code embeds a newline (\n) in the string: >>> print "c:\somehyperlink\name_of_file"
c:\somehyperlink
ame_of_file I think this may work better:
>>> print 'r"{0}"'.format(r"c:\somehyperlink\name_of_file")
r"c:\somehyperlink\name_of_file" hyperlink = r"c:\somehyperlink\name_of_file"
arcpy.CalculateField_management(TableToEdit, "HYPERLINK_FIELD", '{0}"'.format(hyperlink), "PYTHON") I thought I'd add one more thing to this post: how to specify newlines in the Calculate Field tool in ModelBuilder. The interactive tool dialog parser converts "\n" to real newlines in the code box, which doesn't work, so the workaround is to to use chr(10). I've used this as a quick and dirty way to have model builder print a message: Expression: msg()
def msg():
# text = "\n\nThis is\na message to you.\n" # does not work
text = "{0}{0}This is{0}a message to you.{0}".format(chr(10))
return text
... View more
11-07-2012
06:39 AM
|
0
|
0
|
4481
|
|
POST
|
The Tabulate Area tool provides different output fields depending on what it finds in its input, so you can't append them without doing fancy footwork with field maps - not easy in ModelBuilder. Have you tried the Feature Weights To Table tool in the NAWQA toolbox? It creates a long skinny table which you can can tabulate using the Tabulate Weight Table tool (or you could do a pivot table in Excel). ftp://ftpext.usgs.gov/pub/nonvisible/cr/nact
... View more
11-06-2012
09:28 AM
|
0
|
0
|
1836
|
|
POST
|
To clarify the question, I'm not really asking how to parse text, but how to get rid of the errors that prevent me from using the field calculator. This certainly isn't the first time that I've run into this sort of error. It looks like the fastest way to do this is to export and do the manipulations in Excel. Unless you are working with more than 100,000 table rows. 🙂 If you are doing a detailed function like this in Calculate Field, I highly recommend throughly testing it on the python command line first -- much more efficient than running the Calculate Field tool and looking in the geoprocessing results for the error messages. If you are using VBScript, most VBScript functions are similar to VBA (although the language under the hood is quite different), so you can test those using the VBA IDE to test in Excel or Word if you don't have the ArcMap VBA installed. (However, if it gets complicated I stick with Python now, I just use the default VBScript parser for simple calculations.) You can paste entire functions to the ArcMap command line to test them. In fact, I did this with the above function.
>>> def GetNum(text):
text = text.strip()
c1 = list()
for c in text:
if c.isdigit():
c1 += c
else:
c1 += " "
try:
num = float("".join(c1).split()[0])
except:
num = None
return num
<type return>
>>> GetNum("10-Inches Bituminous Concrete 8-Inches Portland Cement ")
10.0
... View more
11-02-2012
08:41 AM
|
0
|
0
|
1287
|
|
POST
|
I want to parse a text field into a floating point field. (e.g.: "10-Inches Bituminous Concrete 8-Inches Portland Cement Concrete 6-Inches Crushed Stone Base" becomes "10") There are of course many ways to do this kind of thing. Here's one way:
>>> text = "10 asdf 12"
>>> [c for c in text if c.isdigit() or c.isspace()]
['1', '0', ' ', ' ', '1', '2']
>>> "".join([c for c in text if c.isdigit() or c.isspace()])
'10 12'
>>>
Here's a function you can use that does this:
def GetNum(text):
text = text.strip()
text = "".join([c for c in text if c.isdigit() or c.isspace()])
try:
num = float(text.split()[0])
except:
num = None
return num
Here's an enhanced version that works if there are no spaces between the numbers:
def GetNum(text):
text = text.strip()
c1 = list()
for c in text:
if c.isdigit():
c1 += c
else:
c1 += " "
try:
num = float("".join(c1).split()[0])
except:
num = None
return num
... View more
11-01-2012
07:04 AM
|
0
|
0
|
1287
|
|
POST
|
However, arcpy.GetMessages is not working as I suppossed. Why GetMessages is working in a Python IDE (like WingIDE) and not in ArcGIS Python Windows? Messages are handled differently in the ArcGIS Desktop python window. For example AddError and AddMessage do not work there, since tools display those messages without you having to explicitly tell it to. Print works though. I have found this in other IDEs as well, sometimes the arcpy.Add... messages do not appear. Entered the following in the ArcMap Python window. Note AddError does nothing.
>>> try:
... raise
... except:
... print "printprint"
... arcpy.AddError("errorprint")
...
printprint
>>>
... View more
11-01-2012
06:40 AM
|
0
|
0
|
2138
|
|
POST
|
Some suggestions below. I was also having issues, more with trying to figure out what "datatype" it wanted when attaching the script to a toolbar. I finally got "Dataset" to work (not coverage like I would have guessed). I believe you were looking for "Coverage Feature Class", which is a subset of "Dataset" "Workspace or Feature Dataset" and "Any Value" for the data type of the other two variables. That last one is a feature class name, so it should be type String. Your script could validate that against the workspace using the arcpy.ValidateTableName method to make sure it's a legal output name. theCoverage = arcpy.GetParameterAsText(0) if theCoverage == '#': GetParameterAsText() will return "" (not "#") if the parameter was not set and you haven't set a default value in the script tool parameters tab. "" evaluates to false in an if, so I often do this:
theCoverage = arcpy.GetParameterAsText(0)
if not theCoverage:
theCoverage = r"c:\_data\_Skwentna07\covers\trans07\arc"
If you think you may run this from Windows instead of from a toolbox, you can support "#" like this:
theCoverage = arcpy.GetParameterAsText(0)
if theCoverage in ["","#"]:
theCoverage = r"c:\_data\_Skwentna07\covers\trans07\arc"
UGH! ((it did work, kind of....wrote to my mxd env which was still set to the default gdb instead of theWorkspace variable. If you apply an environment setting inside the script, it will override any application settings. (Note you can set this parameter in the script tool parameters dialog to default to the app workspace setting.) These settings are local to the script, and will not affect the GP environment of the application that launched the script tool.
theWorkspace = arcpy.GetParameterAsText(1)
if not theWorkspace:
theWorkspace = r"c:\_data\_Skwentna07\Reports\RetroFitDev2\newTest.gdb"
arcpy.env.workspace = theWorkspace
... View more
10-31-2012
08:16 AM
|
0
|
0
|
1798
|
|
POST
|
ERROR 000361: The name starts with an invalid character Failed to execute (CopyFeatures). I believe the error (from CopyFeatures, not Sue's script) is telling you to avoid naming datasets starting with a number. I also suggest avoiding spaces in pathnames, it works most of the time but is just asking for trouble -- something will break when you most need it not to. 000361 : The name starts with an invalid character
... View more
10-31-2012
07:25 AM
|
0
|
0
|
2376
|
|
POST
|
If I want the get error messages in the except clause, the only way is capturing the exception message? Like this way?
except Exception as e:
print e.message Yes.
import arcpy
try:
result = arcpy.GetCount_management("c:/temp/solapes2.shp")
# print tool messages if successful
arcpy.AddMessage(arcpy.GetMessages(0)) # to ArcGIS (script tool)
print arcpy.GetMessages(0) # to stdout
except arcpy.ExecuteError:
# tool failed
arcpy.AddError(arcpy.GetMessages(0)) # to ArcGIS
print arcpy.GetMessages(0) # to stdout
except Exception, msg:
# other errors (say, Python syntax)
arcpy.AddError(str(msg)) # to ArcGIS
print arcpy.GetMessages(0) # to stdout
There are some nice examples here: Arc 10 help: Error handling with Python
... View more
10-30-2012
09:30 AM
|
1
|
0
|
2138
|
| Title | Kudos | Posted |
|---|---|---|
| 1 | 08-11-2021 01:26 PM | |
| 5 | 12-10-2021 04:58 PM | |
| 1 | 02-27-2017 09:30 AM | |
| 2 | 12-04-2023 01:05 PM | |
| 1 | 04-12-2016 10:17 AM |
| Online Status |
Offline
|
| Date Last Visited |
06-19-2024
12:10 AM
|