Select to view content in your preferred language

Why does this toolbox script fail the second time? NameError: global name 'arcpy' is not defined

714
3
05-21-2019 05:51 AM
FredSpataro
Frequent Contributor

Hi All, 

Really simple script attached to a toolbox tool:

  • has a wrapper class to convert logging to arcpy.AddMessage. 
  • no input or output parameters
  • has a main function that adds a single message to the window
  • imports arcpy and logging only
  • runs successfully the first time 
  • fails every time after that until the arcmap/arccatalog app is restarted
  • ArcGIS Desktop 10.6.1

Zip file attached with script and toolbox. Here's the script:

import arcpy 
import logging

class AddMessageHandler(logging.Handler):
    def emit(self, record):
        log_entry = self.format(record)
        arcpy.AddMessage(log_entry)

def main():
    logging.debug("----this is a test----")


if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    
    root_logger = logging.getLogger()
    root_logger.addHandler(AddMessageHandler())

    main()

First run success: 

Subsequent runs fail:

Tags (1)
0 Kudos
3 Replies
DanPatterson_Retired
MVP Emeritus

Works in Python 3.6.8 within ArcGIS Pro.

Are you using python 2.7?

In any event, give this a shot, which also worked flawlessly

import arcpy 
import logging

class AddMessageHandler(logging.Handler):
    def emit(self, record):
        log_entry = self.format(record)
        arcpy.AddMessage(log_entry)

def main():
    logging.basicConfig(level=logging.DEBUG)
    root_logger = logging.getLogger()
    root_logger.addHandler(AddMessageHandler())
    logging.debug("----this is a test----")


if __name__ == '__main__':
    main()
0 Kudos
FredSpataro
Frequent Contributor

Yes it's python 2.7, ArcGIS 10.6.1... ArcGIS Server does not support python 3.x, Pro is not an option.

Moving the logging lines does not change the result.  Runs fine the first time, fails the every time after that. 

0 Kudos
DanPatterson_Retired
MVP Emeritus

Don't know the differences between the server version and *map or *pro. That leave python 2.7 or server or moving emit out of the class and just calling it

0 Kudos