Script in ArcGIS runs only once and throws error the next time

72
1
Friday
NyigamBole
New Contributor II

I am currently using ArcGIS 10.5. I am trying to build a script that would extract time series data from my netCDF file. Below is a sample code. As is required in ArcGIS, I have prepared a script tool that takes in input parameters and gives outputs. 

import arcpy
import os
from netCDF4 import Dataset
import numpy as np

# get the current directory relative to root folder
absolute_path = os.path.dirname(__file__)

# overwrite if previously created files are there
arcpy.AddMessage("Overwriting if previously created files are present in directory")
arcpy.env.overwriteOutput = True

## Process: getting variables
path_netcdf = arcpy.GetParameterAsText(1)
if path_netcdf == '#' or not path_netcdf:
    path_netcdf = os.path.join(absolute_path, "..\\..\\nc_test_files2\\ssp245.nc")

for i in range(3):
    # Storing the lat and lon data into the variables
    try:
        data = Dataset(path_netcdf, 'r')  # The 'r' in the end is a command to read the files
        lon = data.variables['lon'][:]  # This lists the longitude values
        lat = data.variables['lat'][:]  # This lists the latitude values
        arcpy.AddMessage(lon)
        print('working')

    except Exception as e:
        arcpy.AddMessage("Error occurred while reading NetCDF data: {0}".format(str(e)))
    finally:
        data.close()

arcpy.AddMessage("done")

Now, the script tool seems to run perfectly for the first time. However, after that if I want to use the tool again, it throws an error.

netCDFerror.png

Digging deeper led me to the conclusion that the issue starts when line number #22 is run. @HendrikBernert1 raised a similar issue in which he found out a workaround https://community.esri.com/t5/python-questions/arcpy-script-using-sqlalchemy-and-pandas-only-runs/td... . The workaround is to import the modules in the ArcGIS python console before running the script... once that is done, the script runs normally end number of times. However, that is not an actual solution to the script issue.

Is there a way to properly run the script or automate the importing of modules before running the script?

 

 

 

 

 

0 Kudos
1 Reply
David_McRitchie
Esri Contributor

If you have access to ArcGIS Online then you could run this as a scheduled notebook. Through this you could have modules imported first, then the script ran after.

Alternatively ArcGIS Pro also can use Notebooks, but you wouldn't be able to schedule these.

Hopefully that helps, if you have any questions about using Notebooks then please let me know.

Esri UK -Technical Support Analyst
0 Kudos