1

This code original worked when run through the python command window in ArcCatalog. After I added the script to a toolbox I have had all sorts of troubles.

The most frustrating error has been:

NameError: name 'projectGDB' is not defined

Here is a section of the code. Unfortunately, the error persists. Again, the error only occurs when run as a tool from a toolbox. The NameError does not occur when copied and pasted into the command window.

# Import arcpy module & other helpful 
import arcpy, os, xlwt

# Name Project
projectName = arcpy.GetParameterAsText(0)
if projectName == "#" or not projectName:
    projectName = "TEST"

# Create Project Folder
projPath = arcpy.GetParameterAsText(1)
if projPath == "#" or not projPath:
    projPath = "F:\\GIS\\TEST"
arcpy.AddMessage("Folder path for project is " + projPath)
print "Folder path for project is " + projPath

# Create Project Geodatabase
try: 
    arcpy.CreateFileGDB_management(path, projectName, "CURRENT")
except Exception as e:
    print('Error creating gdb {0} at {1}'.format(projectName, projPath))
    print('Exception: {0}'.format(e.message))

# Set Work Environment
projectGDB = os.path.join(path, projectName + ".gdb")
arcpy.env.workspace = projectGDB
arcpy.env.scratchWorkspace = projectGDB
arcpy.env.overwriteOutput = True
arcpy.AddMessage("Workspace is set to " + projectGDB)

#Where is Landcover.gdb located?
landcoverGDB = arcpy.GetParameterAsText(2)
if path == "#" or not landcoverGDB:
    landcoverGDB = "F:\\GIS\\TEST\\Landcover.gdb"

# Load NRI Datasets
building = landcoverGDB + "\\imperv_building"

#[script continues for another 200 lines]

Traceback (most recent call last): File "F:\GIS\Packaged\NRI_sumAcres.py", line 23, in print "Project geodatabase is " + projectGDB NameError: name 'projectGDB' is not defined

Generally speaking, I do not understand why the script ran without error when copied and pasted into the python window of ArcCatalog, but now is dysfunctional once added to a toolbox.

4 Answers 4

4

Don't manually concatenate paths. It leads to errors and makes your code non-portable to other OS's. Use os.path.join instead. For example, replace any instance of

projectGDB = path + projectName + ".gdb"

with :

 projectGDB = os.path.join(path, projectName + ".gdb")

I believe this will solve your problem, since "F:\GIS\TEST" doesn't end in a path separator, you're just sticking the projectName.gdb onto the end of it.

If that doesn't solve it, the line number where python is reporting the exception would help, as would sample output.

4

The problem may be in how you concatenate the variables to create projectGDB. What you're endiing up with for projectGDB is "F:\GIS\TESTTEST.gdb" Notice there's no slash between the path and the gdb name.

I'd suggest using os.path.join(path, projectName + '.gdb') to set projectGDB. Alternately, you could add a slash in front of projectName manually. Also, maybe print out the variable at different stages, see if you're getting what you want. And add some try/except blocks.

6
  • Two answers saying essentially the same thing, +1 to both of you. The problem springs from having no path separator between F:\\GIS\\TEST and TEST.gdb (it doesn't exist and is created in F:\\GIS\TEST\TEST.GDB but the path still doesn't reference it). Manual concatenation can work provided you only want to run the code on one particular OS - but you're right, it's a bad habit to get into and may cause problems later. Commented Dec 18, 2014 at 21:44
  • Thank you. This is helpful and a good best practice. Unfortunately the script still will produce the NameError stating that "projectGDB" is not defined. Traceback (most recent call last): File "\Toolbox.tbx#NRIsumAcres.py", line 23, in <module> NameError: name 'projectGDB' is not defined
    – Caitlin
    Commented Dec 19, 2014 at 18:53
  • It doesn't help to put the same code in the except block as in the try block. Unless you expect a specific error and have a way of dealing with it, the except block is typically used to display more error information and/or at least prevent a program crash if possible. In your 'Create Project Geodatabase' section, add 'print(projectGDB)' to see what the result is. Also, in the if statement, you don't need to recreate projectGDB if it exists. You could instead test for if not os.path.exists and then run the code currently in the else clause. It's not useful to keep setting projectGDB.
    – recurvata
    Commented Dec 19, 2014 at 19:45
  • Does this run as a plain script? If you want to zip and post your code, I'll try to look at it over the weekend.
    – recurvata
    Commented Dec 19, 2014 at 19:46
  • Yes, I understand that it is not useful to keep setting project GDB. However when projectGDB = os.path.join(projPath, projectName + ".gdb") results in the nameError that projectGDB is not defined I tried setting projectGDB in every possible line as a workaround. This is not a part of the original script. I will try the solution you posted below. Again, the script I have works when copied and pasted into the python window, but returns the nameError when used via toolbox. Thank you again for the continue assistance.
    – Caitlin
    Commented Dec 19, 2014 at 21:45
0

Here's a revised version of the first part of your script. Notice you don't even need projectGDB, at least to this stage. Untested, and written as a script, not a tool (except for the GetParameter calls). You should probably check if the path exists as well.

# Import arcpy module & other helpful
import arcpy, os, xlwt

# Name Project
ext = ".gdb"
projectName = arcpy.GetParameterAsText(0)
if projectName == "#" or not projectName:
    projectName = "TEST.gdb"

# make sure projectName has .gdb extension. Ideally, you'd test for invalid
# gdb names as well
if not projectName[-4:] == ext:
    projectName = projectName + ext

print('projectName is: {0}'.format(projectName))   # check that name is correct

# Create Project Folder
projPath = arcpy.GetParameterAsText(1) # renamed variable to avoid reserved word confusion
if projPath == "#" or not projPath:
    projPath = "F:\\GIS\\TEST"
arcpy.AddMessage("Folder path for project is " + projPath)
print('projPath is: {0}'.format(projPath))

# Create Project Geodatabase
try:
    arcpy.CreateFileGDB_management(projPath, projectName, "CURRENT")
except Exception as e:
    # simple error message
    print('Error creating filegdb {0}'.format(os.path.join(projPath, projectName)))
    print('Exception: {0}'.format(e.message))
2
  • Thank you for the advice on changing path to projPath. A good suggestion and best practice to avoid reserved variables. Removing variable projectGDB may not be the best solution. As I expand the code I would like to be able to use both projectGDB and projectName. They are essentially the same since projectGDB[:-4]=projectName, but it seems fine to me to have both. Here is the full code as it currently stands: dropbox.com/s/vlt2ip0hx6ddr3e/NRI_sumAcres.py?dl=0
    – Caitlin
    Commented Dec 22, 2014 at 16:06
  • Thanks again. The solutions provided have the code mostly working. I am no longer having any exceptions or errors with the great advice provided. A few lines of data are not exporting properly, but I have survived the NameError loop! Here is the working code: dropbox.com/s/0iaran7ow8w1oiz/NRI_sumAcre.py?dl=0
    – Caitlin
    Commented Dec 22, 2014 at 18:02
0

Caitlin, here's a tool I created that does what you want, at least as far as your question goes. I haven't added validation, except to set default values, so you may want to do that. In particular, check that filePath exists in case the user manually types in a non-existent path. Note that they can browse to an existing folder, and create a new one. Setting default values and Required eliminates some of your checking code. Also, it would be more appropriate to use AddError than just print(), but this is a start.

import arcpy, sys

gdbName = arcpy.GetParameterAsText(0)
filePath = arcpy.GetParameterAsText(1)   # user able to set file path in tool

# check if filepath exists
if not os.path.exists(filePath):
    print('Path {0} does not exist.'.format(filePath)
    sys.exit()

try:
    arcpy.CreateFileGDB_management(filePath, gdbName)
except Exception as e:
    print('Error creating gdb {0} at {1}'.format(gdbName, filePath))
    print('Exception: {0}'.format(e.message))

Properties projectName filePath

Tool

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.