Select to view content in your preferred language

Creating a geodatabase and setting it to env.workspace

5545
12
Jump to solution
03-23-2017 06:55 AM
EricEagle
Frequent Contributor

Any reason why this wouldn't be working?

import arcpy
import os

basedir = 'C:\\Temp'
gdb_name = 'TestGDB'
gdb = os.path.join(basedir, gdb_name)

if arcpy.Exists(gdb):
    arcpy.env.workspace = gdb
else:
    gdb = arcpy.CreateFileGDB_management(basedir, gdb_name)
    arcpy.env.workspace = gdb‍‍‍‍‍‍‍‍‍‍‍‍

I must not be understanding how .Exists() resolves, for if the gdb already exists, it gives me:

arcgisscripting.ExecuteError: ERROR 000258: Output C:\Temp\TestGDB.gdb already exists

Failed to execute (CreateFileGDB)

If the gdb does not exist, it gives me:

RuntimeError: Object: Error in accessing environment <workspace>

0 Kudos
12 Replies
curtvprice
MVP Alum

This is right on.

eric.eagle It's a little confusing that you have named the result object the same as the gdb full path. A better way to implement this is:

r_gdb = arcpy.CreateFileGDB_management(basedir, gdb_name)

The result object can be used as input parameter to a tool, in which case it will be converted to a path. Or you can convert it to a path yourself with either of these statements -- or just use gdb which you set earlier in the code.

gdb = r_gdb.getOutput(0)
gdb = str(r_gdb)
JoshuaBixby
MVP Esteemed Contributor

This one fascinated me a bit.  On one hand, I am surprised I haven't run into the issue before; but on the other hand, I don't work with the GPEnvironment class much, at least not directly.

Since arcpy.env and arcpy.Exists both go through arcpy.geoprocessing._base, it got me wondering why passing a Result object to one works fine but the other one chokes.  It turns out, one uses gp_fixargs while the other one doesn't.  gp_fixargs is designed to do several things, one of which being extract values from Result objects:

>>> from arcpy.geoprocessing._base import gp_fixargs
>>> res = arcpy.CreateFileGDB_management(r"C:\tmp", "test")
>>> type(res)
<class 'arcpy.arcobjects.arcobjects.Result'>
>>> res
<Result 'C:\\tmp\\test.gdb'>
>>> 
>>> fixed_args = gp_fixargs(res, True)
>>> fixed_args
[u'C:\\tmp\\test.gdb']
>>> fixed_args[0]
u'C:\\tmp\\test.gdb'
>>> 
>>> unicode(res._arc_object)
u'C:\\tmp\\test.gdb'
>>> 

Both arcpy.env and arcpy.Exists check for the presence of an _arc_object property.  Whereas arcpy.Exists uses gp_fixargs, arcpy.env simply tries to use the _arc_object value directly instead of passing it to unicode first.

I guess a question for Esri is why doesn't arcpy.env use gp_fixargs?  I assume it creates some problem somewhere, but who knows, maybe it is simply an oversight.

curtvprice
MVP Alum

Thanks for digging that up, Joshua. You know how much I like a little dirt on how they do stuff underneath what's documented!

Maybe it was kind of a design decision, arcpy.env is not a tool, so you should hand it a string or a non-result object. 

0 Kudos