Fix error in Python code

4045
17
07-31-2020 10:56 AM
KhamisBaroud
New Contributor III

I have Script to create a tool, which converts a comma-delimited text file containing coordinates to a feature class within a database, but an unexpected error appears as in the attached images, is there a workaround for that?
I used ArcMap 10.8 to execute the code!

Please Help...

Script

Error

0 Kudos
17 Replies
JoshuaBixby
MVP Esteemed Contributor

I am glad you got the code running, but your the try and finally blocks still run the risk of generating Python NameErrors that started this thread.  For example, if a user passes a bogus parameter, the exception will be caught but then the finally block will generate a NameError when it tries to delete the cursor that was never created in the first place.

0 Kudos
KhamisBaroud
New Contributor III

Joshua Bixby

Can you explain more? What should I do in order for the code to work properly?
Thank you

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

I agree with an earlier comment by Dan, i.e., just get rid of the try/except/finally blocks altogether.  Looking at the code, your try/except/finally blocks aren't adding any value, i.e., you aren't handling any of the errors that could be generated.  Why trap an error if you aren't doing anything with it?  If you need, or think you need, a try statement; it is best to make them as narrow as possible.  Multiple function/method calls and loops, especially when combined, do not make for a narrow scope.

As David points out above, the print statement doesn't do anything within a Script Tool since there is no console.  Your current code retrieves the messages from the last geoprocessing tool run (that is what GetMessages does), but the messages aren't returned to the user.  Additionally, no errors are returned to the user.  Do you really want the user to think the tool succeeded when it didn't?

Script tools pass errors back to the user by default, so you don't need to try to do it manually. 

WillHouston
New Contributor III

Does the InsertCursor take a lock on the table? If so and the script fails in the for loop, is that lock returned?

0 Kudos
DanPatterson
MVP Esteemed Contributor
0 Kudos
WillHouston
New Contributor III

I'm aware of 'with', but the OP did not use 'with'.

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

When the script tool completes, whether successfully or with errors, all of the variables defined in the script (assuming no globals keyword is used) will go out of scope and the locks will go away.  Using Python 'with' reduces the chances of having problems if the script doesn't complete successfully, e.g., possibly not having the cursor fully flushed before terminating, but the locks will get removed whether cleanly or not.

RandyBurton
MVP Alum

Although the old InsertCursor still works with 10.8, you may wish to convert to the faster da.InsertCursor.