Select to view content in your preferred language

Creating project package fails due to python toolbox

945
6
03-09-2023 05:27 AM
Labels (1)
TorbjørnDalløkken2
Frequent Contributor

Hi.

I'm trying to create a project package in which the ArcGIS Pro project consists of one map with several featurelayers, standalone tables, a task and a python toolbox.  The python toolbox consists of 21 tools each in it's own .py file. The task and the tools within the python toolbox works ok. When I try to create a project package, I get an error which says  ERROR 001659: Consolidating toolbox. 

I've ran the "Analyze Tool for Pro" for all of the tools in the python toolbox, and there are no problems. When trying to run the "Consolidate Toolbox"-tool, I get an error saying ModuleNotFoundError: No module named 'AndelerTilExcelTool', even though the module (tool) exists. Does anyone know what might be wrong?

Here's how I import the modules in the python toolbox (.pyt), the list of modules as been shortened.

# -*- coding: utf-8 -*-
import arcpy
import os
import sys

geovegScripts = os.path.join(os.path.dirname(__file__), "Scripts")
geovegSymbology = os.path.join(os.path.dirname(__file__), "Symbology")
sys.path.append(geovegScripts)

geovegModules = ['AndelerTilExcelTool',
                 'BearbeidAR5Tool',
                 'BearbeidBygningerTool',
                 'BeregnAndelerTool']

for module in geovegModules:
    if module in sys.modules:
        del(sys.modules[module])

from AndelerTilExcelTool import AndelerTilExcel
from BearbeidAR5Tool import BearbeidAR5
from BearbeidBygningerTool import BearbeidBygninger
from BeregnAndelerTool import BeregnAndeler

class Toolbox(object):
    def __init__(self):
        """Define the toolbox (the name of the toolbox is the name of the
        .pyt file)."""
        self.label = "Geoveg PythonToolbox"
        self.alias = "Geoveg verktøy"

        # List of tool classes associated with this toolbox
        self.tools = [AndelerTilExcel, BearbeidAR5, BearbeidBygninger, BeregnAndelerTool]

 

Here are some of the code from AndelerTilExcel, which is saved in the file AndelerTilExcelTool.py

class AndelerTilExcel(object):
    def __init__(self):
        """Define the tool (tool name is the name of the class)."""
        self.label = "Andeler til Excel"
        self.description = ""
        self.canRunInBackground = False

    def getParameterInfo(self):
        """Define parameter definitions"""
        params = None
        return params

    def isLicensed(self):
        """Set whether tool is licensed to execute."""
        return True

    def updateParameters(self, parameters):
        """Modify the values and properties of parameters before internal
        validation is performed.  This method is called whenever a parameter
        has been changed."""
        return

    def updateMessages(self, parameters):
        """Modify the messages created by internal validation for each tool
        parameter.  This method is called after internal validation."""
        return

    def execute(self, parameters, messages):
        """The source code of the tool."""
        try:
            fc_resultat = r"vegsone_bygninger"
            tittel = "Rapport andelsfordeling"
            rapport = r"C:\temp\Andelsfordeling.xlsx"

            #Oppretter ny excel-fil og legger til arbeidsark
            wb = openpyxl.Workbook()
            ws = wb.create_sheet("Andelsfordeling")
    
            #Legger inn overskrifter i arbeidsarket
            ws['A1'] = tittel
            ws['A2'] = "GNR/BNR"
            ws['B2'] = "Partsnummer"
            ws['D2'] = "Andel"

            #Henter informasjon om andelsfordelingen
            felter = ["SAK", "KOMM", "GNR", "BNR", "FNR", "SNR", 
                      "PARTSNUMMER", "ANDEL"]
            with arcpy.da.SearchCursor(fc_resultat, felter, sql_clause=(None, 'ORDER BY PARTSNUMMER DESC')) as cursor:
                linjeNr = 3
                for row in cursor:
                    sak = row[0]
                    kommune = row[1]
                    gnr = row[2]
                    bnr = row[3]
                    fnr = row[4]
                    snr = row[5]
                    partsnummer = row[6]
                    andel = row[7]

                    ws['A'+str(linjeNr)] = "{0}/{1}/{2}/{3}".format(gnr, bnr, fnr, snr)
                    ws['B'+str(linjeNr)] = partsnummer
                    ws['C'+str(linjeNr)] = andel

                    linjeNr += 1                

            #Lagrer Excel-filen
            wb.save(filename=rapport)
        except:
            # Get the traceback object
            tb = sys.exc_info()[2]
            tbinfo = traceback.format_tb(tb)[0]

            # Concatenate information together concerning the error into a message string
            pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
            msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"

            # Return Python error messages for use in script tool or Python window
            arcpy.AddError(pymsg)
            arcpy.AddError(msgs)

            # Print Python error messages for use in Python / Python window
            logging.error(pymsg)
            logging.error(msgs)
        return

    def postExecute(self, parameters):
        """This method takes place after outputs are processed and
        added to the display."""
        return

  

As mentioned the python toolbox works ok, but not when consolidated or packaged.

0 Kudos
6 Replies
DanPatterson
MVP Esteemed Contributor

Is this in Pro 3.0.x or 3.1?

related Error 001659 when Creating Project Template contai... - Esri Community

with no resolution

@ShaunWalbridge  could you pass this on


... sort of retired...
0 Kudos
TorbjørnDalløkken2
Frequent Contributor

It's in ArcGIS Pro 3.0.x

0 Kudos
JerryClark4
Occasional Contributor

Pro works with Python 3.x. Is the script you are trying to use Python 3.x or 2.7. If 2.7 then you may need to upgrade your script to 3.x before it will work. Just a suggestion.

0 Kudos
TorbjørnDalløkken2
Frequent Contributor

@JerryClark4 I've used Python 3.x since the toolbox is for use in ArcGIS Pro 🙂

0 Kudos
TorbjørnDalløkken2
Frequent Contributor

I finally got something working here. In my scripts-folder, I forgot to add a __init__.py file. When adding this file, and changing my imports  like this, then it started working.

geovegModules = ['Scripts.AndelerTilExcelTool',
                 'Scripts.BearbeidAR5Tool',
                 'Scripts.BearbeidBygningerTool',
                 'Scripts.BeregnAndelerTool']

for module in geovegModules:
    if module in sys.modules:
        del(sys.modules[module])

from Scripts.AndelerTilExcelTool import AndelerTilExcel
from Scripts.BearbeidAR5Tool import BearbeidAR5
from Scripts.BearbeidBygningerTool import BearbeidBygninger
from Scripts.BeregnAndelerTool import BeregnAndeler

 But there's still one problem. I'm trying to define a logging handler in my toolbox (in class Toolbox __init__(self):

handler = logging.FileHandler(filename=r'C:\temp\Geoveg.log')
        formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
        handler.setFormatter(formatter)
        handler.setLevel(logging.DEBUG)
        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)
        logger.handlers = [handler]		

 When trying to consolidate this, I get an FileNotFoundError. [Errno 2] No such file or directory: 'C:\\commondata\\temp\\Geoveg.log'

0 Kudos
HannesZiegler
Esri Contributor

@TorbjørnDalløkken2 based on the FileNotFoundError it looks like the specified log file C:\temp\Geoveg.log can't be found, and Python is looking for the file in C:\commondata\temp instead. Perhaps the directory doesn't exist, or you don't have access to it?

0 Kudos