ArcPy Traceback (most recent call last): error - python

I used Model Builder to convert feature classes within a geodatabase into shapefiles into a preexisting folder. It ran successfully. However, when i exported the Model into a Python Script and ran it in Python, I get an error saying:
Traceback (most recent call last):
File "C:\Users\Mark.Novicio\Desktop\New folder\FSA_Counties_delivered_by_GISO\Updated_Iterators.py", line 13, in
arcpy.ImportToolbox("Model Functions")
The python script is attached in the image:

ArcPy code exported from ModelBuilder often needs a lot of tweaking, although it can be a moderately useful starting point.
IterateFeatureClasses_mb is the python-code of a ModelBuilder only tool.
This tool is intended for use in ModelBuilder and not in Python scripting.
Since you want to use Python instead, you need to use a normal iterator (generally, a for loop running through a list of feature classes). You can automatically build the list with arcpy.ListFeatureClasses, and then just loop:
# set the workspace
arcpy.env.workspace = Test_gdb
# get a list of feature classes in arcpy.env.workspace
listFC = arcpy.ListFeatureClasses()
# iterate
for fc in listFC:
#
# code to do to fc
#
If you're only planning to use that list of feature classes once, call ListFeatureClasses in the for loop:
for fc in arcpy.ListFeatureClasses():
In either case, you'll need to look at FeatureClassToFeatureClass for outputting a shapefile once you get your loop working :)

Related

'UnityEnvironment' object has no attribute 'behavior_spec'

I followed this link to doc to create environment of my own.
But when i run this
from mlagents_envs.environment import UnityEnvironment
env = UnityEnvironment(file_name="v1-ball-cube-game.x86_64")
env.reset()
behavior_names = env.behavior_spec.keys()
print(behavior_names)
Game window pop up and then terminal show error saying
Traceback (most recent call last):
File "index.py", line 6, in <module>
behavior_names = env.behavior_spec.keys()
AttributeError: 'UnityEnvironment' object has no attribute 'behavior_spec'
despite the fact that this is the exact snippet as shown in the documentation.
I created environment by following this (it make without brain) and i was able to train the model by .conf file. Now i wanted to connect to python API.
You need to use stable documents and stable repo( RELEASE_TAGS ) to achieve stable results. Unity ML Agents changes it's syntax every few months so that is problem if you are following master branch.
env.get_behavior_spec(behavior_name: str)
Should solve your problem.
https://github.com/Unity-Technologies/ml-agents/blob/release_2/docs/Python-API.md

Feeding list position as parameter to arcpy.SymDiff_analysis function

New to python.
I have two feature datasets, Input features (NewDemoFC) and Update Features (ExistingFC) with 5 feature classes each. One set contains demolished features, the other set contains all active features. The objective is to compare the two and wherever the demolished features (from NewDemoFC) overlap with an active feature (from ExistingFC), delete the overlapping active features (from ExistingFC) and output a new feature class.
I want to use the while function and be able to feed a particular position from the list for both input features and update feature parameters. Also would like to maintain the same names and order for output feature class names.
Trying to achieve the results of the below model for a dataset with multiple files as the SymDiff_analysis tool doesn't work on more than one FC as input, unless you add each feature class as a line item, specifying input, output and any intermediate temporary files. This is not practical for a dataset with 100 odd feature classes.
enter image description here
CODE IS AS UNDER
# Import arcpy module
import arcpy
# Set environment to generate new input feature class list and count
arcpy.env.workspace = "T:\eALP_Update.gdb\Point_DemoNew"
NewDemoFC = arcpy.ListFeatureClasses()
NewDemoFCCount = len(NewDemoFC)
# Set environment to generate existing feature class list
arcpy.env.workspace = "T:\eALP_Update.gdb\Point_InputExisting"
ExistingFC = arcpy.ListFeatureClasses()
E_PointFeatures_ActiveOnly = []
i = 0
#arcpy.env.workspace = "T:\eALP_Update.gdb\Point_ActiveExisting"
while i < NewDemoFCCount:
# Process: Symmetrical Difference (2)
arcpy.SymDiff_analysis(NewDemoFC[i], ExistingFC[i], E_PointFeatures_ActiveOnly[i], "ALL", "0.01 Feet")
i = i + 1
ERROR I GET IS AS UNDER
Traceback (most recent call last):
File "C:\Python27\ArcGIS10.5\Lib\site-packages\pythonwin\pywin\framework\intpyapp.py", line 345, in OnFileRun
scriptutils.RunScript(None, None, showDlg)
File "C:\Python27\ArcGIS10.5\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 353, in RunScript
del main.file
AttributeError: file
5
[u'Demo_New_UTILITYPOINT', u'Demo_New_ROADPOINT', u'Demo_New_AIRPORTSIGN', u'Demo_New_AIRPORTCONTROLPOINT', u'Demo_New_AIRFIELDLIGHT']
5
[u'UtilityPoint', u'RoadPoint', u'AirportSign', u'AirportControlPoint', u'AirfieldLight']
Traceback (most recent call last):
File "C:\Python27\ArcGIS10.5\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript
exec codeObject in main.dict
File "T:\Data\GOAA\eALPUpdates\Point_2-SymmetricalDifferenceOnly.py", line 41, in
arcpy.SymDiff_analysis(NewDemoFC[i], ExistingFC[i], E_PointFeatures_ActiveOnly[i], "ALL", "0.01 Feet")
IndexError: list index out of range
[Dbg]>>>
What you want to do is use a for loop that iterates over each feature class to avoid the odd indexing process you have going on inside your call to arcpy.SymDiff. For example, the use of i to index E_PointFeatures_ActiveOnly (an empty list) as an output path won't work. To do this the way you want to, you'll need to dynamically generate file names. Make sure that the output folder is empty when you do this to avoid naming conflicts. The code you have also duplicates everything for each folder, so we can define functions to eliminate that, that way you can re-use it easily. Lastly, you really want to avoid altering global variables like arcpy.env.workspace multiple times - the function below for this is really verbose, but since it's a function, you only have to do it once! I'll assume you have access to arcgis version >= 10.1 The following code is long and untested, but I imagine it should do the trick:
import arcpy
arcpy.env.workspace = "T:\eALP_Update.gdb\Point_ActiveExisting"
def getFCs(folderOne, folderTwo):
"""Get feature classes from two folders"""
from os.path import join
x = []
y = []
folders = [folderOne, folderTwo]
for folder in folders:
for paths, directory, filenames in arcpy.da.Walk(
folder,
topdown=True,
followlinks=False,
datatype='FeatureClass',
type='ALL'):
for file in filenames:
if folder == folder[0]:
x.append(join(directory, file))
else:
y.append(join(directory, file))
return x, y
def batchSymDiff(inFolder, updateFolder, joinAttr, clusterTolerance):
"""Performs SymDiff analysis for every feature in a set of folders"""
inFeatures, updateFeatures = getFCs(inFolder, updateFolder)
for fc1, fc2 in zip(inFeatures, updateFeatures):
output = fc2.replace(".shp", "_sym.shp") # this naming pattern assumes ".shp" ending
arcpy.SymDiff_analysis(fc1, fc2, output, joinAttr, clusterTolerance)
# set variables for batch process
inFolder = "T:\eALP_Update.gdb\Point_DemoNew"
updateFolder = "T:\eALP_Update.gdb\Point_InputExisting"
joinAttr = "ALL"
clusterTolerance = "0.01"
# execute batchSymDiff
batchSymDiff(inFolder, updateFolder, joinAttr, clusterTolerance)
This code is probably more verbose than it has to be, but doing it this way means you can avoid changing global env vars over and over - a risky business since the errors it causes are really difficult to diagnose sometimes - and it makes your code reusable. Also note that it eliminates the need to use a "manual" counter (i). Hope it helps! I suggest testing the code on test data first.

Error when using scipy.misc.imread inside the loop

I have a case similar to this question.
Faced it when training deep learning model and reading images inside the loop.
scipy.misc.imread(rawImagePath).astype(numpy.float32)
The code above is working perfectly the vast majority of the time, but sometimes I get the error:
batch 90, loading batch data...
x path: /path_to_dataset/train/9.png
2017-10-31 20:23:34.531221: W tensorflow/core/kernels/queue_base.cc:294] _0_input_producer: Skipping cancelled enqueue attempt with queue not closed
Traceback (most recent call last):
File "train.py", line 452, in <module>
batch_X = load_data(batch_X_paths)
File "/path_to_my_script/utilities.py", line 85, in load_data
x = misc.imread(batch_X_paths[i]).astype(np.float32)
TypeError: float() argument must be a string or a number
The difference is: I have a fixed set of files and I do not write new ones to the directory.
I made a little research and figured out that error comes not from
numpy.astype()
but from
PIL.Image.open()
scipy.misc uses PIL under the hood.
Also, I managed to reproduce this bug in Jupyter Notebook. I made a loop with reading/astype code inside. After few seconds (the size of my test .png is about 10MB) I interrupt cell's execution and voila!
error reproduced in Jupyter Notebook
Inside scipy.misc sources there is a code like this:
def imread(name, flatten=False, mode=None):
im = Image.open(name)
return fromimage(im, flatten=flatten, mode=mode)
Image here is a PIL object. And Image.open() gives us 0-dimension list when interrupting cell.
I have tried Evert's advice and made a loop with try/except, but sometimes it fails even after 5 attempts.
Also I tried OpenCV imread() method instead of scipy.misc and sometimes it fails too. Error text:
libpng error: incorrect data check
So... I ran out of ideas.

PyWin32 using MakePy utility and win32com to get Network Statistics

This question is in continuation to my previous question.
I am trying to get Network Statistics for my Windows 7 system using PyWin32.
The steps I followed:
1) Run COM MakePy utility and than select network list manager 1.0
type library under type library.
2) Above process generated this python file.
Next I created the object of class NetworkListManager(CoClassBaseClass) using
import win32com.client as wc
obj = wc.Dispatch("{DCB00C01-570F-4A9B-8D69-199FDBA5723B}")
Now I am trying to access the methods provided by the above created object obj.
help(obj) gave me
GetNetwork(self, gdNetworkId= <PyOleEmpty object>)
Get a network given a Network ID.
IsConnected
Returns whether connected to internet or not
//Other methods removed
So, now when I use
>>> obj.IsConnected
True
It works fine.
Now the problem I am facing is how to use GetNetowrk method because when I try to use it
>>> obj.GetNetwork()
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
ret = self._oleobj_.InvokeTypes(2, LCID, 1, (9, 0), ((36, 1),),gdNetworkId
com_error: (-2147024809, 'The parameter is incorrect.', None, None)
I also tried creating PyOleEmpty object by using pythoncom.Empty and passed it as a paremeter but no luck.
I understand GetNetwork require NetworkID as a parameter but the method GetNetworkId is defined in INetwork class.
So my question is how to use classes defined in the python file created using MakePy utility which are not CoClass.
It looks like the way to get to the Network objects is to enumerate them using GetNetworks:
networks=obj.GetNetworks(win32com.client.constants.NLM_ENUM_NETWORK_CONNECTED)
for network in networks:
print (network.GetName(), network.GetDescription())
Using the network ids will be problematic. They're defined as raw structs, so they will need to be passed using Records. Pywin32's support for the IRecordInfo interface is still somewhat weak.

Error using cv.CreateHist in Python OpenCV as well as strange absence of certain cv attributes

I am getting an error (see below) when trying to use cv.CreateHist in Python. I
am also noticing another alarming problem. If I spit out all of the attributes
of the cv module into a file, and then I search them, I find that a ton of
common things are missing.
For example, cv.TermCriteria() is not there; cv.ConnectedComp is not there; and
cv.CvRect is not there.
Everything about my installation, with Open CV 2.2, worked just fine. I can plot
images, make CvScalars, and call plenty of the functions, like cv.CamShift...
but there are a dozen or so of these hit-or-miss functions or data structures
that are simply missing with no explanation.
Here's my code for cv.CreateHist:
import cv
q = cv.CreateHist([1],1,cv.CV_HIST_ARRAY)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: x9y��
The weird wingding stuff is actually what it spits out at the command line, not a copy-paste error. Can anyone help figure this out? It's incredibly puzzling.
Ely
As for CvRect, see the documentation. It says such types are represented as Pythonic tuples.
As for your call to CreateHist, you may be passing the arguments in wrong order. See createhist in the docs for python opencv.

Categories

Resources