|
POST
|
These scripts are a couple from a series that I use to create features /tables and maintain a geodatabase. I like MySQL’s SHOW CREATE TABLE and wanted to do a similar workflow with arcpy. The scripts above use arcpy’s CreateTable and TableToDomain tools with the xlrd module to create and populate a domain. I use a list of lists for my field definitions which makes it easy to change field types, aliases, etc. I maintain an Excel workbook for my domains. By naming the worksheet tabs with the domain name, additional data can be stored in the workbook and not cause problems with the process. The worksheets for domains should have at least two columns (CODE and DESCRIPTION), but other related columns could be added. If the domain is being used to track employee activities, the domain code can link to the employee table and provide access to related information. I’ve attached a sample workbook. The first script uses the field name lists to create a table. Then it reads the workbook tab with the domain name and populates the table. The second script reads specific tables (named in a list) and converts them into a coded value domain. Hope this helps.
... View more
03-09-2019
08:13 PM
|
1
|
4
|
14388
|
|
POST
|
I've had some time to do some tests. While there is a delete() option for Text Elements, there is no such option for Picture Elements. However, you can make the image disappear if you set either the width or height to 0. Once it has been set to zero, it does not appear that you can bring the image back by adjusting the height/width. The name, elementPositionX, elementPositionY and imageSource parameters still contain their original values. So this does not appear to be a clean deletion. (If you are working inside ArcMap, you may need to refresh the view to see the changes.) for elm in arcpy.mapping.ListLayoutElements(mxd, "PICTURE_ELEMENT"):
elm.elementHeight = 0.0 # setting this to 0 will also set elementWidth to 0
... View more
03-07-2019
07:59 PM
|
1
|
1
|
1951
|
|
POST
|
I've deleted text elements with arcpy, so it should be possible with something like (untested): import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Project\Project.mxd")
for elm in arcpy.mapping.ListLayoutElements(mxd, "PICTURE_ELEMENT"):
elm.delete() # delete all picture elements
# or if using name or sourceImage properties
# if elm.name == "Photo":
# if elm.sourceImage == r"C:\Project\Data\NewPhoto.bmp":
# elm.delete()
mxd.save()
del mxd See PictureElement for some information., but it doesn't really discuss .delete(). Hope this helps.
... View more
03-07-2019
05:22 PM
|
0
|
0
|
1951
|
|
POST
|
Try: row[1] = assignName[row[0]] # to access dictionary, use square brackets not ()
... View more
03-07-2019
04:04 PM
|
1
|
0
|
4766
|
|
POST
|
I like using dictionaries: sourceFC = "somefeature"
sourceFieldsList = [ 'location_id', 'latitude', 'longitude' ]
whereExp = "objectid IN {0}".format(objectIDList)
uniqueLocIDs = {r[0]:(r[1:]) for r in arcpy.da.SearchCursor(sourceFC, sourceFieldsList, where_clause=whereExp)}
# { location_id: ( latitude, longitude), .... )
... View more
02-27-2019
08:01 PM
|
1
|
0
|
2568
|
|
POST
|
You might try something like: import arcpy
fc = r"C:\path\to\file.gdb\feature"
# add field (may want to check if they exist first)
arcpy.AddField_management(fc, "winner", "TEXT", "", "", 50,
"winner", "NULLABLE")
arcpy.AddField_management(fc, "percent", "DOUBLE", "", "", "",
"percent", "NULLABLE")
# list of fields with votes, and for winner and winning percent
fields = [ 'socialdemo', 'radikale', 'konservative', 'socialistisk', 'liberal', 'winner', 'percent' ]
with arcpy.da.UpdateCursor(fc, fields) as cursor:
for row in cursor:
votes = row[:5] # fields with vote counts or percentages
# get maximum vote / percent
winTotal = max(votes)
# get winner / party
winner = fields[votes.index(max(votes))]
# other options if needed
# # if votes, you can sum them
# vTotal = sum(votes)
# # and calculate percentage
# percent = float(winTotal)/vTotal
row[5] = winner # party
row[6] = winTotal # percent
cursor.updateRow(row) Hope this helps.
... View more
02-27-2019
09:46 AM
|
1
|
0
|
1994
|
|
POST
|
Untested, but perhaps something like: import arcpy
import requests
import os
import urllib
class ToolValidator:
def __init__(self):
self.params = arcpy.GetParameterInfo()
def initializeParameters(self):
# (initializeParameters code here)
return
def updateParameters(self):
if self.params[0].altered:
if self.params[0].value: # a url has been entered in first parameter
url = self.params[0].value
path = urllib.parse.urlparse(url).path
base_file_name = os.path.basename(path)
scratch_folder = arcpy.env.scratchFolder
self.params[1].value = os.path.join(scratch_folder, base_file_name)
return
def updateMessages(self):
# (updateMessages code here)
return Then use: output_file_name = arcpy.GetParameterAsText(1).
... View more
02-25-2019
11:40 PM
|
0
|
0
|
1018
|
|
POST
|
And to confirm, you replaced the validator code with the appropriate section from above and then refreshed the tool?
... View more
02-25-2019
11:19 AM
|
0
|
1
|
1547
|
|
POST
|
I had used the select all button the tool interface provides without a problem. I did not try the deselect button but will check it out later.
... View more
02-25-2019
09:54 AM
|
0
|
3
|
1547
|
|
POST
|
Thanks for attaching the files. From that I noticed, you wanted the option to select multiple fields. I modified the validator code in your other post for this option. I believe that the encoding issues arise because the tool interface appears to pass values that contain special characters in single quotes. From the tool printout, note line 7 below. The two fields with special characters are enclosed within single quotes and inside double quotes. Executing: encodingtest C:\path\to\folder\encoding 'Chl_A (µg/L)';'Temperature (°C)';pH
Start Time: Sun Feb 24 19:55:53 2019
Running script encodingtest...
Table view field names: ['Original_file_&_sheet', 'Campaign', 'Profile_No', 'Date', 'Longitude (degrees_east)', 'Latitude (degrees_north)', 'Depth (m)', 'Temperature (\xc2\xb0C)', 'pH', 'Chl_A (\xc2\xb5g/L)', 'UID', 'UIDGraph']
fieldnamesliste from parameter: ["'Chl_A (\xc2\xb5g/L)'", "'Temperature (\xc2\xb0C)'", 'pH'] By trimming the quotes, I was able to get your script to work. Here's the section I modified; it starts around line 142 in the original code. The .decode("utf-8") in line 4 below may be the result of some of the encoding/decoding you were doing earlier in the script. I'm not sure what of that code can safely be removed. def PrintPlot(gs, gsNr, table, fieldname, min, max, xlabelname, colorL):
if fieldname[0] == "'":
arcpy.AddMessage("apostrophe found")
fieldname = fieldname[1:-1].decode("utf-8")
xlabelname = fieldname
fields = [fieldname, "Depth (m)"] Hope this helps.
... View more
02-24-2019
06:48 PM
|
1
|
1
|
10444
|
|
POST
|
I posted updated validator code above. I hadn't considered that you are using a multivalue selection list. In addition, there is a check that needed to be done to see if any fields were selected. I also updated the single selection check but commented it out. Since some of your fields are using extended characters, those field name parameters will be inside single quotes. See also: Generating a choice list from a field Generating a multivalue choice list Hope this helps.
... View more
02-24-2019
06:35 PM
|
1
|
6
|
6138
|
|
POST
|
The error also indicates line 24, but I would expect it to be around 17. Your other scripts have 31 and 32 lines. Did something else get added? You might try the first script you posted with just the change "email_cursor" to "cursor" in line 16. The only other issue I see at this time could be the where clause in that same line. The date may need to be in single quotes, but that depends on your database/server. "Date_Approved = {}".format(tdy)
# or
"Date_Approved = '{}'".format(tdy)
... View more
02-22-2019
04:54 PM
|
1
|
0
|
4943
|
|
POST
|
In your second script you dropped "for row in cursor:" (line 17 in first script). Then you need to change back lines 20 and 23 to "row[1]" and "row[2]". with arcpy.da.SearchCursor(layer, field, "Date_Approved = {}".format(tdy)) as cursor:
for row in cursor:
print ("Match Found!")
SERVER = "xxxxxxxxxxx"
FROM = "xxxxxxxxxxx"
TO = "Applicant <{}>".format(row[1])
CC = "xxxxxxxxxxxxxx"
SUBJECT = "Utility Encroachment Approach Approved"
MSG = "\n {},\n".format(row[2]) + " " + "This is to notify you that your utility encroachment has been approved. Please use the following link to view additional details www. .com"
TEXT = (MSG)
MESSAGE = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT)
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, [TO]+[CC], MESSAGE)
... View more
02-22-2019
03:55 PM
|
1
|
2
|
4943
|
|
POST
|
I put your code in a debugging template found on this page: Debugging a ToolValidator class. I only made a few changes, mostly using self.params[0], etc. to access the parameters. I kept the MakeTableView because it aided in identifying the field types. It might be possible to read the text file's first line directly to get the field names, and the second line to determine field types. Print statements will work in the debug script, but they will not display once it is placed in the tool's validator section (and could cause errors). For this reason, they have been commented out. My first tool parameter was a folder type, the second was a string (for the field names). Here's my debug test code: import arcpy
# Load the toolbox and get the tool's parameters, using the tool
# name (not the tool label).
#
arcpy.ImportToolbox(r"C:\Path\to\tool\box\dropdown.tbx")
params = arcpy.GetParameterInfo("DropdownTest")
# refresh toolbox in Catalog or ArcMap if changes made to tool/parameters
# also close and restart Python IDE
# Set required parameters
# input, folder
params[0].value = r"C:\Users\Randy\Documents\ArcGIS\PythonScripts\test\text2field\encoding"
# input, string ['Temperature (\xc2\xb0C)', 'pH', 'Chl_A (\xc2\xb5g/L)']
# params[1].value = 'Chl_A (\xb5g/L)' # for 1 value
params[1].values = [ 'pH', 'Chl_A (\xb5g/L)' ] # for multiple values
# ToolValidator class block ------------------------------------------------------------
#
class ToolValidator(object):
"""Class for validating a tool's parameter values and controlling
the behavior of the tool's dialog."""
def __init__(self):
"""Setup arcpy and the list of tool parameters."""
self.params = arcpy.GetParameterInfo()
def initializeParameters(self):
"""Refine the properties of a tool's parameters. This method is
called when the tool is opened."""
return
def updateParameters(self):
"""Modify the values and properties of parameters before internal
validation is performed. This method is called whenever a parameter
has been changed."""
if self.params[0].altered:
if self.params[0].value: # a folder has been entered in first parameter
arcpy.env.workspace = filedir = self.params[0].value
list_of_files = arcpy.ListFiles("*.txt")
firsttable=list_of_files[0]
# print(firsttable)
# print(filedir)
complete_filename = str(filedir)+"\\"+firsttable
# print(complete_filename)
if arcpy.Exists("kivu_tview"): # if tableview exists then delete it
arcpy.Delete_management("kivu_tview")
table=arcpy.MakeTableView_management(complete_filename, "kivu_tview")
desc = arcpy.Describe(table)
# fieldnamesoriginal=[field.name for field in desc.fields] # collects all fieldnames
# print "Table view field names: "+str(fieldnamesoriginal)
fieldselectlist=[]
for ofields in desc.fields:
ftype=ofields.type
fname=ofields.name
if ftype in ["Double","Integer","Long"]:
# print fname
if fname not in ["Profile_No","Longitude (degrees_east)","Latitude (degrees_north)","Bot. Depth (m)","Depth (m)"]:
with arcpy.da.SearchCursor(table, fname) as calcursor:
for calcrow in calcursor:
if calcrow[0] is not None:
fieldselectlist.append(fname)
break
# print fieldselectlist
arcpy.Delete_management("kivu_tview","Table View") # delete table view
# for multiple choice
try:
if self.params[1].values: #if this parameter has seleted values
oldValues = self.params[1].values #set old values to the selected values
except Exception:
pass
self.params[1].filter.list = sorted(fieldselectlist) #set the filter list equal to the sorted values
newValues = self.params[1].filter.list
try:
if len(oldValues): # if some values are selected
self.params[1].values = [v for v in oldValues if v in newValues] # check if seleted values in new list,
# if yes, retain the seletion.
except Exception:
pass
# for single choice
# self.params[1].filter.list = sorted(fieldselectlist) # set second parameter filter list
# if self.params[1].value not in self.params[1].filter.list:
# self.params[1].value = self.params[1].filter.list[0] # default to first item in list
return
def updateMessages(self):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
return
# Call routine(s) to debug ------------------------------------------------------------------------------------------
#
validator = ToolValidator()
validator.updateParameters()
validator.updateMessages()
# testing results
print(arcpy.GetMessages())
print u"Folder: {}".format(params[0].value)
# print u"Fields: {}".format(params[1].value) # for 1 value
print u"Fields: {}".format(params[1].values) # for multiple values
Once I was happy with the debug test, I pasted the ToolValidator section into the tool's validator. Hope this helps.
... View more
02-21-2019
09:46 PM
|
0
|
4
|
6138
|
| Title | Kudos | Posted |
|---|---|---|
| 1 | 10-27-2016 02:23 PM | |
| 1 | 09-09-2017 08:27 PM | |
| 2 | 08-20-2020 06:15 PM | |
| 1 | 10-21-2021 09:15 PM | |
| 1 | 07-19-2018 12:33 PM |
| Online Status |
Offline
|
| Date Last Visited |
02-12-2026
07:13 PM
|