Runtime error Traceback - SelectLayerByAttribute

9164
13
Jump to solution
04-07-2015 11:47 AM
SilvanStöckli
New Contributor III

Hello

Every time I execute my python-script in the end it says

Runtime error  Traceback (most recent call last):   File "<string>", line 52, in <module>   File "c:\program files (x86)\arcgis\desktop10.3\arcpy\arcpy\management.py", line 7211, in SelectLayerByAttribute raise e ExecuteError: ERROR 000229: Cannot open Rest\Kartenausschnitte A3 mit Aussparung Legende. 1:2500 und 1:3000 Failed to execute (SelectLayerByAttribute).

So this is the "bad" part of my script. lyrkartenausschn is "Rest\Kartenausschnitte A3 mit Aussparung Legende. 1:2500 und 1:3000"

cursor = arcpy.da.SearchCursor(lyrkartenausschn, [seitenzkartenausschn])

    seitenliste = int(19)

    del seitenliste

    seitenliste = []

    for row in cursor:

        seitenliste.append(int(row[0]))

    print seitenliste

    for seite in seitenliste:

        for elm in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):

            if elm.name == seitex:

                elm.text = str(seite)

                pfdausgabePDFeinzeln = pfadausgpdf[0:-4] +"_"+ str(seite) + ".pdf" #Path

        arcpy.SelectLayerByAttribute_management (lyrkartenausschn, "NEW_SELECTION", seitenzkartenausschn + " = " +  str(seite))

        mxd.dataDrivenPages.exportToPDF(pfdausgabePDFeinzeln, "SELECTED") #PDF Export

        mxd.dataDrivenPages.printPages(druckername, "SELECTED") #  Print

    mxdspeicher = ausgpdfmxd + "\\" + bewirtschafter + ".mxd"

    mxd.saveACopy(mxdspeicher)

    del row

    del cursor

    del seite

    del seitenliste

    del elm

    arcpy.RefreshActiveView()

There's a lot of things I'm doing bevore. So if I leave the "bad" part, it loops trough the whole script perfectly. If I add this part, the error appears.

I also tryed to add the line "arcpy.SelectLayerByAttribute_management (lyrkartenausschn, "CLEAR_SELECTION")" at the verry bottom, but then the same error appears for this line.

So what's wrong with the code? do I have to del something more? or "deactivate" data driven pages? (maybe it's a problem because it's still printing? but then how can I make it wait until it's finished?

thank you for your help!

0 Kudos
1 Solution

Accepted Solutions
XanderBakker
Esri Esteemed Contributor

This may be difficult to solve without the data and only part of the code. If the problem is caused by an access error of the layer contained in variable "lyrkartenausschn", you should have a look at how the layer is defined (this part is not included in the code posted).

I also came across this issue: 43104 - 000229: Cannot open  which indicates that if you have background processing switched on, it may cause this problem.

View solution in original post

13 Replies
JoshuaBixby
MVP Esteemed Contributor

What if you comment out only the two mxd.dataDrivenPages lines, does the code work then?

0 Kudos
SilvanStöckli
New Contributor III

I will try tomorrow.

If it works, what would you succest to do?

0 Kudos
SilvanStöckli
New Contributor III

I tried it.
And the same error popped up...

0 Kudos
SilvanStöckli
New Contributor III

Does anyone know if it makes a difference whether I run the code directly in the python shell in ArcGIS or run it seperately?

At the moment I run it in ArcGIS. Do you think it would be worth the time to change all the parameters and try running it seperately?

0 Kudos
CarlSunderman
Occasional Contributor

What exactly are you trying to do?

0 Kudos
SilvanStöckli
New Contributor III

Well. The whole script prints (and exports to pdf) all parcels of each person. it exports only those extens where there are parcels of this person. it adds the extent number and the x of y page number.

so the part of the code above does the following: in my layer ("lyrkartenausschn") I have a column with the page numbers ("x" of x of y). the cursor reads the number and adds it to the "seitenliste" (= page-list). so for every page in my page-list it replaces the numer in the textfield "seitex" (the "x" of x of y) and creates a new PDF-export-path (with the name of the person + page number). then it exports the pdf to that path and prints the extent.

After that it should loop back and do the same for the next person. That's where it should do a selection of my layer ("lyrkartenausschn") again. but it doesn't. if I quote out the script part shown above, it loops trough all the data perfectly.

0 Kudos
XanderBakker
Esri Esteemed Contributor

Since the error message refers to line 52 and the SelectLayerByAttribute tool, I suppose it refers to this line.

arcpy.SelectLayerByAttribute_management (lyrkartenausschn, "NEW_SELECTION", seitenzkartenausschn + " = " +  str(seite))

The format of the where clause depends on the data source. It is normally better to let arcpy how your field should be referenced. What is not clear to me is the data format of the field "seite". You convert is to integer when you read and append it to the list and later on you convert it to string. What is the field type of "seite"?

You could replace the line above for:

# in case 'seite' is integer
where = "{0} = {1}".format(arcpy.AddFieldDelimiters(lyrkartenausschn, seitenzkartenausschn), seite)
# in case 'seite' is string
where = "{0} = '{1}'".format(arcpy.AddFieldDelimiters(lyrkartenausschn, seitenzkartenausschn), seite)

arcpy.SelectLayerByAttribute_management(lyrkartenausschn, "NEW_SELECTION", where)

Please use syntax highlighting for your code (see: Posting Code blocks in the new GeoNet )

0 Kudos
SilvanStöckli
New Contributor III

thank you for your post. and also for the hint for syntax highlighting!

so here's the original code again.

cursor = arcpy.da.SearchCursor(lyrkartenausschn, [seitenzkartenausschn])
    seitenliste = int(19)
    del seitenliste
    seitenliste = []
    for row in cursor:
        seitenliste.append(int(row[0]))
    print seitenliste
    for seite in seitenliste:
        for elm in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):
            if elm.name == seitex:
                elm.text = str(seite)
                pfdausgabePDFeinzeln = pfadausgpdf[0:-4] +"_"+ str(seite) + ".pdf" #Path
        arcpy.SelectLayerByAttribute_management (lyrkartenausschn, "NEW_SELECTION", seitenzkartenausschn + " = " +  str(seite))
        mxd.dataDrivenPages.exportToPDF(pfdausgabePDFeinzeln, "SELECTED") #PDF Export
        mxd.dataDrivenPages.printPages(druckername, "SELECTED") #  Print
    mxdspeicher = ausgpdfmxd + "\\" + bewirtschafter + ".mxd"
    mxd.saveACopy(mxdspeicher)
    del row
    del cursor
    del seite
    del seitenliste
    del elm
    arcpy.RefreshActiveView()

One thing I saw when reading your message: Line 52 isn't the line you guessed. I forgot to post it, sorry.

it's the following (Line 1):

    arcpy.SelectLayerByAttribute_management(lyrkartenausschn, "NEW_SELECTION", seitenzkartenausschn + " IS NOT NULL")
    arcpy.CalculateField_management(lyrkartenausschn, seitenzkartenausschn,  "NULL", "VB")

This part of the code selects the "x in x of y" from the previous iteration and sets them to "NULL". So first it selects de extents which were used the previous times, then calculates the field to set the values to "NULL". As I see now, it's not really necessary to select it first, since I want to set all the values in that column to "NULL". But anyway, I can't see, why it shouldn't work.


Another thing I saw is that I must have forgotten to delete the first "seitenliste" (line 2+3) when I wrote the code.
I think there's no use for it. In the end, I think it must be integer, since in line 6 I make an integer out of the "row".

I convert the seitenliste to integer so I can make a for loop on it (line 8). and then in line 12 and 13 I need the same number to be written in the textfield and also to the path, so I think I really need to convert it twice?

So tomorrow I will try your suggestions and also delete the unnecessary rows.

An other question: is there a page where I can read about the   .format ?  I don't really understand how this works.

Thank you for your help! 🙂

0 Kudos
SilvanStöckli
New Contributor III

So I changed the code. Now it looks like this:

(what i posted bevore was from line 58 to the end).

#start code Block
mxd = arcpy.mapping.MapDocument("CURRENT")  #wählt das aktuelle mxd aus
opentext = open (bewtextdok)  #öffnet das Textdokument bewtextdok
for line in opentext: #iteration durch alle linien des bewtextdok

##################################################################
# path and definition qry
    bewirtschafter = line[0:-1]  #"extraktion" des bewirtschafternamens aus dem textfeld
    pfadausgpdf = ausgpdfmxd + "\\" + bewirtschafter + ".pdf" #Zusammenführen des PDF-Ausgabepfades
    pfadausgmxd = ausgpdfmxd + "\\" + bewirtschafter + ".mxd" #Zusammenfügen des MXD-Ausgabepfades
    print pfadausgpdf
    print pfadausgmxd
    print "*****************************************"
    query = qryweiteres + spueberschr + "=" + "'" + bewirtschafter + "'" #zusammenfügen der Query
    print query
    lyr = arcpy.mapping.Layer(qrylyr)    #wählt den layer für die query aus
    lyr.definitionQuery = query    #führt die query aus

##################################################################
# change legend text
    #Bewirtschafter Name
    for elm in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):
        if elm.name == bewtxtbox:
            elm.text = bewirtschafter[0:31]
    print "Bewirtschafter ersetzt"
    print "************************"
    # Seitenzahl
        #Seitenzahl auf "" setzen
    arcpy.CalculateField_management(lyrkartenausschn, seitenzkartenausschn,  "NULL", "VB")
        #selektieren der Kartenausschnitte - auch für drucken und exportieren
    arcpy.SelectLayerByLocation_management (lyrkartenausschn, "", lyr, "", "NEW_SELECTION") #selektiert die Kartenausschnitte, welche den lyr (mit qry) enthalten
        #Neue Seitenzahl für die Markierten Seiten setzen (Nummerierung 1 bis X)

    lyr = lyrkartenausschn # replace this with your layer name  
    fields = ['Nummer', 'OID@']  
    # set up a dictionary and counter  
    dict = {}  
    counter = 0# Use list comprehension to build a list of Nummer values combined with ObjectID values as a tuple  
    dict = {(row[0:]):0 for row in arcpy.da.SearchCursor(lyr, fields)}  
    # Sort the list and put the counter into a dictionary for fast random access  
    for value in sorted(dict.keys()):  
        counter += 1  
        dict[value] = counter  
    # Write back to the layer with an update cursor using the dictionary. Change 'COUNTER' to your counter field  
    fields = ['Nummer', 'OID@', seitenzkartenausschn]  
    with arcpy.da.UpdateCursor(lyr, fields) as cursor:  
        for row in cursor:  
            row[2] = dict[(row[0],row[1])]  
            cursor.updateRow(row)  

        #seitenzahl total
    anzahlseiten = arcpy.GetCount_management(lyrkartenausschn) #Auslesen der Anzahl makrierten Seiten
    for elm in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):
        if elm.name == vony:
            elm.text = str(anzahlseiten)
    print "Anzahl Seiten = " + str(anzahlseiten)

#print and export for every page 
    cursor = arcpy.da.SearchCursor(lyrkartenausschn, [seitenzkartenausschn])
    seitenliste = []
    for row in cursor:
        seitenliste.append(int(row[0]))
    print seitenliste  #dieser ganze for-loop generiert die "seitenliste", welche alle zu druckenden Seiten beinhaltet
    for seite in seitenliste:
        for elm in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):
            if elm.name == seitex:
                elm.text = str(seite)
                pfdausgabePDFeinzeln = pfadausgpdf[0:-4] +"_"+ str(seite) + ".pdf" #Pfad bei einzelner PDF-Ausgabe

        where = "{0} = {1}".format(arcpy.AddFieldDelimiters(lyrkartenausschn, seitenzkartenausschn), seite)  
        arcpy.SelectLayerByAttribute_management(lyrkartenausschn, "NEW_SELECTION", where)
        mxd.dataDrivenPages.exportToPDF(pfdausgabePDFeinzeln, "SELECTED") #PDF Export
        #mxd.dataDrivenPages.printPages(druckername, "SELECTED") # Drucken
        arcpy.SelectLayerByAttribute_management(lyrkartenausschn, "CLEAR_SELECTION")
    mxdspeicher = ausgpdfmxd + "\\" + bewirtschafter + ".mxd"
    mxd.saveACopy(mxdspeicher)
    del row
    del cursor
    del seite
    del seitenliste
    del elm
    arcpy.RefreshActiveView()

what happens now:

Runtime error  Traceback (most recent call last):   File "<string>", line 52, in <module>   File "c:\program files (x86)\arcgis\desktop10.3\arcpy\arcpy\management.py", line 3453, in CalculateField     raise e ExecuteError: ERROR 000229: Cannot open Rest\Kartenausschnitte A3 mit Aussparung Legende. 1:2500 und 1:3000 Failed to execute (CalculateField). 

Line 52 is line 28 in the code above.

maybe somehow my layer "lyrkartenausschn"  (=Rest\Kartenausschnitte A3 mit Aussparung Legende. 1:2500 und 1:3000) gets locked.

First I thought it mus be because of the data driven pages. but then i quoted out both ddp-lines and the same error occured. so there must be another mistake in my script.

maybe this can give a hint: when I run the script (even with the lines 59 to 74 quoted out) the error occurs now. After the error I'm not able to run the script again. First I need to close ArcMap and then run it again.

0 Kudos