Why doesn't the script break if the Version exists?
Traceback (most recent call last): File "C:\Users\jnmiller\Desktop\Create User Version.py", line 30, in arcpy.CreateVersion_management(sdeConnection, parentVersion, versionName, "PROTECTED") File "C:\Program Files (x86)\ArcGIS\Desktop10.5\ArcPy\arcpy\management.py", line 18244, in CreateVersion raise e ExecuteError: ERROR 001148: Cannot create a version with the specified name. Failed to execute (CreateVersion).
# Name: SDE_CreateVersion
# Description: Creates a new SDE version
# Import system modules
import arcpy, time, smtplib, os
# Set local variables
sdeConnection = "Database Connections\NEO_1.sde"
parentVersion = "sde.DEFAULT"
versionName = os.environ.get( "USERNAME" )
fullPath = os.path.join("Windows Credentials: EGAS", versionName)
existingVersion = os.path.join("Version Currently Exists: ",versionName)
createVersion = os.path.join("Version Created: ",versionName)
print("Searching for User Credentials..")
time.sleep(2)
print(fullPath)
time.sleep(3)
print("Checking SDE for existing Credentials..")
for version in arcpy.da.ListVersions(sdeConnection):
if version.name.split(".")[0] == versionName:
time.sleep(3)
print(existingVersion)
time.sleep(5)
break
else:
# Execute CreateVersion
arcpy.CreateVersion_management(sdeConnection, parentVersion, versionName, "PROTECTED")
time.sleep(3)
print(createVersion)
time.sleep(5)
1 Answer 1
It fails because the version creation block is inside the loop over existing version. As it is now, the code loads the list of version, reads the name of the 1st one, and if the owner is different than the one in versionName
, it creates the version.
To fix it, you must move the version creation block outside of the loop. You create a flag variable versionFound
that you set to false
by default, and to true
if the version is found. Later, if versionFound == False
, you can safely create the new version
versionFound = False
for version in arcpy.da.ListVersions(sdeConnection):
if version.name.split(".")[0] == versionName:
time.sleep(3)
print(existingVersion)
time.sleep(5)
versionFound = True
break
# Execute CreateVersion
if not versionFound:
arcpy.CreateVersion_management(sdeConnection, parentVersion, versionName, "PROTECTED")
time.sleep(3)
print(createVersion)
time.sleep(5)
Making users wait for nothing with all the sleep
is not considered as best practices.
for
loop doesn't make sense: listing existing versions to create them can't work. While you can use any user's version, you cannot create anthing but your own, so periods are not permitted in the name string (31 chars max, leading alpha, remainder alphanumeric)