Python arcpy обновление цикла курсора прервано - PullRequest
0 голосов
/ 13 ноября 2018

Этот сценарий был создан для очистки таблицы строк, у которой нет аналога в другой таблице (это необходимо сделать с помощью arcpy, поскольку таблица является классом пространственных объектов с включенным архивированием из ESRI). Я тестирую этот сценарий на производстве, поэтому вместо того, чтобы фактически удалить строки, я просто использую счетчик. Однако когда значение счетчика «excluidos» составляет около 310000, сценарий просто останавливается. Есть некоторый предел памяти в arcpy-курсоре обновлений? (обычно я получаю сообщение об ошибке памяти Python, что здесь не так) Или здесь есть какая-то логическая проблема, которую я пропускаю?

# -*- encoding: utf-8 -*-
import os.path, sys, time
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from arcpy import da

pasta = os.path.abspath(os.path.join( os.path.dirname(__file__), '..', 'modelos'))

fc = 'Database Connections/geodados em arcgissql01.sde/geodados.sigamgeo.fis_vistorias_aia_tcra'
fc2 = 'Database Connections/geodados em arcgissql01.sde/geodados.sigamgeo.tb_fis_vistorias_aia_tcra'
workspace = os.path.dirname(fc)

campos = [
    "NIS"
    ,"Sigla"]

campos2 = ["NIS", "DataElabRTV"]

print str(time.strftime('%x %X'))
print 'Iniciando busca de registros no workspace: ' + fc2

lista = []
listIg = []

with da.SearchCursor(fc2, (campos2)) as sc:
    for row in sc:
        if row[0] <> None:
            lista.append(row[0])

print str(time.strftime('%x %X'))
print 'Iniciando exclusao de registros no workspace: ' + fc

try:
    edit = da.Editor(workspace)
    print str(time.strftime('%x %X'))
    print 'Iniciando edicao.'
    edit.startEditing(False, False) #undo/multiuser
    print str(time.strftime('%x %X'))
    print 'Iniciando operacao.'
    edit.startOperation()
except Exception as e:
    print e
    sys.exit(0)

print str(time.strftime('%x %X'))
print 'Iniciando exclusao.'
excluidos = 0
ignorados = 0
multiplo = 100000
try:
    with da.UpdateCursor(fc, (campos)) as cursorExc:
        for row in cursorExc:
            if row[0] <> None:
                verifExcec = False
                for reg in lista:
                    if reg == int(row[0]):
                        verifExcec = True
                if verifExcec:
                    listIg.append(reg)
                    ignorados += 1
                    continue
                else:
                    #cursorExc.deleteRow()
                    excluidos += 1
            else:
                ignorados += 1
            #verifica se o contador e igual ao multiplo definido para emitir o aviso
            if (excluidos % multiplo == 0):
                print u"{0} - {1} ".format(time.strftime('%x %X'), excluidos) + u" registros excluídos até o momento."


except Exception as e:
    print e

print str(time.strftime('%x %X'))
print str(excluidos) + ' registros excluidos.'

print str(time.strftime('%x %X'))
print str(ignorados) + ' registros ignorados.'

try:          
    # Stop the edit operation.
    print str(time.strftime('%x %X'))
    print 'Encerrando operacao.'
    edit.stopOperation()

    # Stop the edit session and save the changes
    print str(time.strftime('%x %X'))
    print 'Encerrando edicao.'
    edit.stopEditing(True)
except Exception as e:
    print e

listIg.sort()
for nis in listIg:
    print nis

1 Ответ

0 голосов
/ 14 ноября 2018

Я думаю, что ограничение на arcpy, поэтому я должен был задать вопрос на GIS Stack Exchange.В любом случае, я «решил» проблему гораздо более медленным решением, запустив и остановив редакцию для каждого исключения:

print str(time.strftime('%x %X'))
print 'Iniciando busca de registros no workspace: ' + fc2

listAIA = []
listVist = []
listIg = []
adicionados = 0
ignorados = 0

with da.SearchCursor(fc2, (campos2)) as sc:
    for row in sc:
        if row[0] <> None:
            listVist.append(row[0])

with da.SearchCursor(fc, (campos)) as sc1:
    for row in sc1:
        verifExcec = False
        if row[0] <> None:
            for vist in listVist:
                if int(row[0]) == vist:
                    verifExcec = True
            if verifExcec:
                ignorados += 1
                listIg.append(row[0])
                continue
            else:
                listAIA.append(row[0])
                adicionados += 1
        else:
            ignorados += 1
            listIg.append(row[0])

print str(time.strftime('%x %X'))
print 'Iniciando exclusao de registros no workspace: ' + fc

col_1 = 'NIS'
excluidos = 0
multiplo = 100000

for reg in listAIA:  
    expressao = '"' + col_1 + '" = ' + str(reg)
    try:
        edit = da.Editor(workspace)
        edit.startEditing(False, False) #undo/multiuser
        edit.startOperation()
    except Exception as e:
        print e
        sys.exit(0)

    try:
        with da.UpdateCursor(fc, (campos), expressao) as cursorExc:
            for row in cursorExc:
                #cursorExc.deleteRow()
                excluidos += 1
                print u"{0} - {1} ".format(time.strftime('%x %X'), excluidos) + u" registros excluídos até o momento."

    except Exception as e:
        print e   

    try:          
        # Stop the edit operation.
        edit.stopOperation()    
        # Stop the edit session and save the changes
        edit.stopEditing(True)
    except Exception as e:
        print e

    if (excluidos % multiplo == 0):
        print u"{0} - {1} ".format(time.strftime('%x %X'), excluidos) + u" registros excluídos até o momento."

print str(time.strftime('%x %X'))
print str(excluidos) + ' registros excluidos.'

print str(time.strftime('%x %X'))
print str(ignorados) + ' registros ignorados.'
...