So I wrote this code
spec = raw_input("Enter the specimen number: ")
naorimp = raw_input("Native or Implant (N/I)? ")
trial = raw_input("Trial number: ")
typana = raw_input("What do you want to analyze (contact area[CA]/contact pressure[CP])? ")
try :
if typana.lower() == "cp" :
naorimp = naorimp.upper()
TSfilnm = 'pressure'+spec+naorimp.upper()+trial+'.txt'
else :
naorimp = naorimp.upper()
TSfilnm = 'area'+spec+naorimp+trial+'.txt'
TSfile = open(TSfilnm, 'r')
myofilnm = 'accelerometer'+spec+naorim.upper()+trial+'.txt'
print myofilnm
myofile = open(myofilnm, 'r')
except :
print "File could not be found."
print "Please re-run the program."
exit()
print "OK"
I want to open a file based on user's input and several parameters (specimen no., native or implant, trial no., and type of analysis.) The file is already in the same folder as the python file code. But when I run the program I always end up with except statements (File could not be found. Please re-run the program). I have double-checked the real file name and the string inside the TSfilnm variable, and they are the same. However, the TSfile could not be executed.
P.S. The file name in my folder is: pressure3N1.txt, area3N1.txt, accelerometer3N1.txt
You are missing a p in the variable name in this line
myofilnm = 'accelerometer'+spec+naorim.upper()+trial+'.txt'
should be
myofilnm = 'accelerometer'+spec+naorimp.upper()+trial+'.txt'
Also don't use 'except' alone during development, it will only hide errors like in this case. It's better to do something like.
import sys
try:
#Your_code_here
except:
print sys.exc_info()[1]
#Any other code you wanna run
I have this python script that basically selects a point by it's ID, then selects all points within a distance and returns only a subset of those that match the type field. i.e. find all hospitals within 3 miles of this location..
My python script works, does what it's supposed to. So I create a GP service from it. Add the service back into the map and run it. Now I notice no matter what distance I use, the data doesn't change. If I delete the created Featureclass to see if it's really working. It does not create a new featureclass but it says it completed successfully.
Now the weird part, if I hit the GP service at the rest endpoint with the parameters it says it works but returns no records. I've been careful to avoid schema locks when using the Rest endpoint ArcMap and ArcCatalog are closed.
It's like the GP service doesn't have permission to write to the sde database, However my sde connection works fine on my PC.
Any ideas?
import arcpy, os, string
from arcpy import env
db = r"Connection to racdev1.sde"
theworkspace = r"Connection to racdev1.sde"
arcpy.env.workspace = theworkspace
arcpy.env.overwriteOutput = True
#facilityID = '1249'
facilityID = arcpy.GetParameterAsText(0)
#facilityIDType= 'PFI'
facilityIDType = arcpy.GetParameterAsText(1)
thedistance = arcpy.GetParameterAsText(2)
#thedistance = '3 miles'
#withindistance = "3 Miles"
withindistance = thedistance + ' Miles'
sql_query = "\"%s\" = '%s'" % ("ID", facilityID)
sql_query2 = "\"%s\" = '%s'" % ("IDTYPE", facilityIDType)
# Local variables:
Facilities = "DOHGIS.NYSDOH_CI_DATA"
featLayer = "thePts"
arcpy.MakeFeatureLayer_management(Facilities, featLayer)
# Process: Select Layer By Attribute
arcpy.SelectLayerByAttribute_management(featLayer, "NEW_SELECTION", sql_query)
# Process: Select Layer By Location 311
arcpy.SelectLayerByLocation_management(featLayer, "WITHIN_A_DISTANCE",featLayer, withindistance, "NEW_SELECTION")
#print " now for the subset"
arcpy.SelectLayerByAttribute_management("thePts", "SUBSET_SELECTION", sql_query2 )
# creaate the new featureclss..
arcpy.CopyFeatures_management("thePts",'DOHGIS.NYSDOH_FacilitiesQuery')
#print "Done"
this script is supposed to select features within distance in two layers based on some their characteristics one feature will get a score (example: water pipes crossing naturally sensitive areas like rivers, the type of that river and its permanency matter in the scoring, so each type will be selected then used in select by lactation function to give water pipes that are within a distance its score
this is the error I get when i run these codes:
Executing: SelectLayerByLocation water_mains WITHIN_A_DISTANCE Just_selected "2.5 Meters" NEW_SELECTION
Start Time: Thu Sep 25 15:21:09 2014
ERROR 999999: Error executing function.
A column was specified that does not exist.
A column was specified that does not exist.
Failed to execute (SelectLayerByLocation).
the select layer by location is in a script that is called by another script (main script)
the main script :
def main():
try:
import arcpy
from arcpy import env
# pathing to avoid retyping
env.workspace = "C:/Users/abusheikan/Desktop/prev_files/RiskAnalysisModel"
dataPath = 'C:\\Users\\abusheikan\\Desktop\\prev_files\\RiskAnalysisModel\\ToolData2'
arcpy.env.overwriteOutput = True
import imp
##Defines INPUT variables
#some variable wont be used but are there for future use, I'm starting off as simple as possible
creekLayer = dataPath + "\\ENVIRONMENTAL\\OHN_WaterCourse.shp"
PipeLayer=dataPath + "\\SERVICES\\water_mains.shp"
nameField = 'ROW_1'
scoreField = 'ROW_SCORE1'
crossingField = 'CROSS_ROW1'
ROWfield = 'ROW_TRUE1'
diaField='INTERNAL_D'
rangeVal= 416
Field = 'WARTERCOURS'
Field2='PERMANENCY'
arcpy.MakeFeatureLayer_management(PipeLayer,"water_mains")
inFeatures = "water_mains"
#The following lists contain road classes. Format is (a, b, c,d) such that a is the creek class name,
#b is an average permencnacy of flow, c is the width, nd d is the xscore to be given .
#Lower value of c means lower criticality.
creeks = [('Vertual Flow','intermittent',10,1),
('Vertual Connector','intermittent', 10,2),
('Vertual Flow','Permanent', 10,1),
('Vertual Connector', 'Permanent', 10,2),
('Ditch','Intermittent',5,3),
('Ditch','Permanent',5,4),
('Stream','Intermittent',5,3),
('Stream','Intermittent',5,4)]
## the following isnt used yet
creeks2 = [('Vertual Flow','intermittent',10,1),
('Vertual Connector','intermittent', 10,2),
('Vertual Flow','Permanent', 10,1),
('Vertual Connector', 'Permanent', 10,2),
('Ditch','Intermittent',5,3),
('Ditch','Permanent',5,4),
('Stream','Intermittent',5,3),
('Stream','Intermittent',5,4)]
## This codeblock isnt utilized yet and will always return row_score, it is supposed to adjusts the value of ROW_SCORE
##based on whether the water main crosses a creek, by looking up the value in CROSS_ROW1 feild that is obtained later on
expression = "crossing(!CROSS_ROW1!,!ROW_SCORE1!)"
codeblock = """def crossing(crosses, row_score):
if crosses != 0:
return 5
else:
return row_score"""
except:
arcpy.AddError("Definitions failed")
arcpy.AddMessage(arcpy.GetMessages())
try:
## pathing to a funtion to be called
fpath = 'C:\\Users\\abusheikan\\Desktop\\prev_files\\RiskAnalysisModel\\Scripts\\'
## defining the function pathing we retyped anyway for debugging purpuses.
functions = imp.load_source('functions', 'C:\\Users\\abusheikan\\Desktop\\prev_files\\RiskAnalysisModel\\Scripts\\functions_creeks.py')
## check check :-p
arcpy.AddMessage("Funtions Loaded")
except:
arcpy.AddMessage("Functions not loaded")
try:
##Clear all selections, because otherwise commands will be applied only to selected features, why? I ont know pls explain where this is
## supposed to be used and where not to. THANKs!
arcpy.SelectLayerByAttribute_management(inFeatures, "CLEAR_SELECTION")
arcpy.AddMessage("Selected")
##This new field will show the road overlying the pipe. Default value of "no Creek" will be assigned.
arcpy.AddField_management(inFeatures, nameField, "TEXT")
arcpy.CalculateField_management(inFeatures, nameField, '"No Creek"')
##This field will contain a score for the highest creek class over the pipe.
## Default of 0 means no creeks
arcpy.AddField_management(inFeatures, scoreField, "SHORT")
arcpy.CalculateField_management(inFeatures, scoreField, 1)
arcpy.AddField_management(inFeatures, crossingField, "SHORT")
## arcpy.AddField_management(mainRoadLayer, ROWfield, "FLOAT",3,1)
## arcpy.CalculateField_management("t_Pavement_Line", ROWfield, expressionROW, "PYTHON_9.3", codeblockROW)
except:
#Report error
arcpy.AddError("Could not create new fields")
#Report error messages
arcpy.AddMessage(arcpy.GetMessages())
try:
## functions.roadclass_loop is a function that loops through all creek classes in
## a list, selects the water mains within a distance of each one, and assigns the
## appropriate score. Full script is in the called function.
## the following s a failed test so never mind that commented out line, it may ciome in handy so left it in there
## arcpy.MakeFeatureLayer_management(PipeLayer,
## "JUST_MADE",str(dialField) + " <= "+ str(rangeVal))
## calls creek_loop funtion() i think here is where the error is created pls check the inputs they may be where problem is! but i cant see anything wrong with them.
functions.roadclass_loop(creeks, creekLayer, Field, inFeatures, "WITHIN_A_DISTANCE",
nameField, scoreField)
arcpy.AddMessage("small pipes")
## same as b4 but with the second tuple list.
functions.roadclass_loop(creeks2, creekLayer, Field, inFeatures, "WITHIN_A_DISTANCE",
nameField, scoreField)
arcpy.AddMessage("BIG PIPES")
## functions.roadclass_loop(provincial, provincialLayer, Field3, inFeatures, "INTERSECT",
## "", crossingField)
## If the CROSS_ROW field has a nonzero value (i.e. if the water main crosses a large road)
## the road class score will be increased to 5(the maximum).
## inserts the scores into the
arcpy.CalculateField_management(inFeatures, scoreField, expression, "PYTHON_9.3", codeblock)
except:
arcpy.AddMessage("Could not run")
arcpy.AddMessage(arcpy.GetMessages())
if __name__== "__main__":
main()
the called function is:
def test():
## import arcpy
arcpy.AddMessage("This function works")
##def roadclass_loop(listOfClassTuples, sourceLayer, fieldName, targetLayer,
## outputField1, outputField2):
def roadclass_loop(listOfClassTuples, sourceLayer, fieldName, targetLayer, crossingType,
outputField1, outputField2):
import arcpy
from arcpy import env
env.workspace = "C:/data/"
##try:
for creekclass in listOfClassTuples:
(classname, Permanency, creekWidth, score) = creekclass
bufferDistance = creekWidth*0.5
try:
if crossingType == "INTERSECT":
stringBuffer = ""
else:
stringBuffer = "%s Meters" % str(bufferDistance)
except:
arcpy.AddMessage("its here")
arcpy.MakeFeatureLayer_management(sourceLayer, "Just_selected",
fieldName + "= '"+ classname + "'")
#arcpy.MakeFeatureLayer_management("Just_Selected", "JUST_SELECTED", FieldName2+" = '"+ Permanency + "'")
arcpy.SelectLayerByLocation_management(targetLayer, crossingType,
"Just_selected", stringBuffer, "NEW_SELECTION")
classname = classname.lower()
if outputField1!= "":
arcpy.CalculateField_management(targetLayer, outputField1, classname )
arcpy.CalculateField_management(targetLayer, outputField2, score )
arcpy.Delete_management("Just_selected")
arcpy.SelectLayerByAttribute_management(targetLayer, "CLEAR_SELECTION")
##except:
# arcpy.AddMessage("Function failed")
#arcpy.AddMessage(arcpy.GetMessages())
See this question on the GIS StackExchange: Points in Polygon Count: Error with arcpy.selectLayerByLocation_management . They made a mistake when calling MakeFeatureLayer_management, but the error was thrown by SelectLayerByLocation_management. You may have a similar situation.
In your case, are you confident that the feature class stored in dataPath + "\\ENVIRONMENTAL\\OHN_WaterCourse.shp" has a field called WARTERCOURS? Is there maybe a typo there? (The word WARTERCOURS caught my attention; Google says you're the first person on the Internet to use it.)
Is your listOfClassTuples, which is being fed by your creeks variable, supposed to be set of fields within your creekLayer (dataPath + "\ENVIRONMENTAL\OHN_WaterCourse.shp)?
Sorry - My questions is how can I change a file object within a function from a different function?
I've been trying to work out this error in my first python script for too long now, Dr Google and the forums aren't helping me too much, but I'm hoping you can.
I have a looping function that generates alot of data and I would like to output it to a text file, and create a new text file after the third loop.
I have 2 functions defined, one to create the data hashes, the other to create the new files.
The new files are being created as expected (aaa.txt, baa.txt...etc) but the "hashit" function only ever writes to the first file (aaa.txt) even though the others are being created.
I have tried fo.close() fo.flush(), as well as referencing fo in the functions but can't seem to make it work. Also I've moved the fo.write from the function to the main body.
I have included a cut down version of the code that I've been using to troubleshoot this issue, the real one has several more loops increasing the string length.
Thanks in advance
import smbpasswd, hashlib
base = '''abcdefghijklmnopqrstuvwxyz '''
# base length 95
print(base)
baselen = len(base)
name = 'aaa.txt'
fo = open(name, "w")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace
pw01 = 0
pw02 = 0
pw03 = 0
def hashit(passwd):
#2
# Need to install module
# sudo apt-get install python-smbpasswd
hex_dig_lm = smbpasswd.lmhash(passwd)
hex_dig_ntlm = smbpasswd.nthash(passwd)
#print '%s:%s' % smbpasswd.hash(passwd)
hash_md5 = hashlib.md5(passwd)
hex_dig_md5 = hash_md5.hexdigest()
print(passwd)
print(hex_dig_lm)
print(hex_dig_ntlm)
print(hex_dig_md5)
hashstring = passwd +","+ hex_dig_lm +","+ hex_dig_md5 + '\n'
fo.write(hashstring);
def newfile(name):
fo.flush()
fo = open(name, "a")
print("-------newfile------")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print('NewFile : ' + name)
raw_input("\n\nPress the enter key to exit.")
# add 3rd digit
while (pw03 < baselen):
pwc03 = base[pw03]
name = pwc03 + 'aa.txt'
fo.close
newfile(name);
pw03 += 1
while (pw02 < baselen):
pwc02 = base[pw02]
pw02 += 1
while (pw01 < baselen):
pwc01 = base[pw01]
pw01 += 1
passwd = pwc03 + pwc02 + pwc01
hashit(passwd);
else:
pw01 = 0
else:
pw02 = 0
else:
pw03 = 0
In your newfile() function, add this line first:
global fo
I am currently trying to populate 2 fields. They are both already created within a table that I want to populate with data from existing feature classes. The idea is copy all data from desired feature classes that match a particular Project #. The rows that match the project # will copy over to blank template with the matching fields. So far all is good except I need to push the data from the OBJECT ID field and the Name of the Feature Class in to 2 fields within the table.
**def featureClassName(table_path):
arcpy.AddMessage("Calculating Feature Class Name...")
print "Calculating Feature Class Name..."
featureClass = "FeatureClass"
SDE_ID = "SDE_ID"
fc_desc = arcpy.Describe(table_path)
lists = arcpy.ListFields(table_path)
print lists
with arcpy.da.SearchCursor(table_path, featureClass = "\"NAME\"" + " Is NULL") as cursor:
for row in cursor:
print row
if row.FEATURECLASS = str.replace(row.FEATURECLASS, "*", fc):
cursor.updateRow(row)
print row
del cursor, row
else:
pass**
The Code above is my attempt, out of many to populate the field with the Name of the Feature class.
I have attemped to do the same with the OID.
**for fc in fcs:
print fc
if fc:
print "Making Layer..."
lyr = arcpy.MakeFeatureLayer_management (fc, r"in_memory\temp", whereClause)
fcCount = int(arcpy.GetCount_management(lyr).getOutput(0))
print fcCount
if fcCount > 0:
tbl = arcpy.CopyRows_management(lyr, r"in_memory\temp2")
arcpy.AddMessage("Checking for Feature Class Name...")
arcpy.AddMessage("Appending...")
print "Appending..."
arcpy.Append_management(tbl, table_path, "NO_TEST")
print "Checking for Feature Class Name..."
featureClassName(table_path)
del fc, tbl, lyr, fcCount
arcpy.Delete_management(r"in_memory\temp")
arcpy.Delete_management(r"in_memory\temp2")
else:
arcpy.AddMessage("Pass... " + fc)
print ("Pass... " + fc)
del fc, lyr, fcCount
arcpy.Delete_management(r"in_memory\temp")
pass**
This code is the main loop for the feature classes within the dataset that i create a new layer/table to use for copying the data to the table. The data for Feature Class Name and OID dont have data to push, so thats where I am stuck.
Thanks Everybody
You have a number of things wrong. First, you are not setting up the cursor correctly. It has to be a updateCursor if you are going to update, and you called a searchCursor, which you called incorrectly, by the way. Second, you used = (assignment) instead of == (equality comparison) in the line "if row.FEATURECLASS ... Then 2 lines below that, your indentation is messed up on several lines. And it's not clear at all that your function knows the value of fc. Pass that as an arg to be sure. Bunch of other problems exist, but let's just give you an example that will work, and you can study it:
def featureClassName(table_path, fc):
'''Will update the FEATURECLASS FIELD in table_path rows with
value of fc (string) where FEATURECLASS field is currently null '''
arcpy.AddMessage("Calculating Feature Class Name...")
print "Calculating Feature Class Name..."
#delimit field correctly for the query expression
df = arcpy.AddFieldDelimiters(fc, 'FEATURECLASS')
ex = df + " is NULL"
flds = ['FEATURECLASS']
#in case we don't get rows, del will bomb below unless we put in a ref
#to row
row = None
#do the work
with arcpy.da.UpdateCursor(table_path, flds, ex) as cursor:
for row in cursor:
row[0] = fc #or basename, don't know which you want
cursor.updateRow(row)
del cursor, row
Notice we are now passing the name of the fc as an arg, so you will have to deal with that in the rest of your code. Also it's best to use AddFieldDelimiter, since different fc's require different delimiters, and the docs are not clear at all on this (sometimes they are just wrong).
good luck, Mike