POST
|
Hello! I am trying to loop through a list in python and the script is only processing the first database and not the remainder of the list. Where is the script wrong? 1 # import packages
2 import os, arcpy, time, smtplib
3 # setup workspace and SDE databases in folder
4 for dirpath, dirnames, filenames in os.walk(r'C:\Users\XXX\AppData\Roaming\Esri\Desktop10.7\ArcCatalog\SDE'):
5 for file in dirpath:
6 print filenames
7 string = 'C:/Users/XXX/AppData/Roaming/Esri/Desktop10.7/ArcCatalog/SDE/'
8 new_list = [string + x for x in filenames]
9 print new_list
10 for database in new_list:
11 # Block new connections to the database.
12 print('The database is no longer accepting connections{}'.format(database))
13 arcpy.AcceptConnections(database, False)
14 # Wait 5 minutes
15 time.sleep(5)
16 # Disconnect all users from the database.
17 print("Disconnecting all users")
18 arcpy.DisconnectUser(database, "ALL")
19 # Run the compress tool.
20 print("Running compress")
21 arcpy.Compress_management(database)
22 # Allow the database to begin accepting connections again
23 print("Allow users to connect to the database again")
24 arcpy.AcceptConnections(database, True)
25 # Rebuild indexes in database(s)
26 print("Rebuilding indexes on the system tables")
27 arcpy.RebuildIndexes_management(database, "SYSTEM")
28 # Updating statistics in database(s)
29 print("Updating statistics on the system tables")
30 arcpy.AnalyzeDatasets_management(database, "SYSTEM")
31 print ("Finished")
32 break
33 break
34 break
... View more
09-16-2019
06:22 AM
|
0
|
3
|
660
|
POST
|
I am trying to send a email using the smtplib package and am getting the following error: Script: import smtplib server_ssl = smtplib.SMTP_SSL('smtp.office365.com', xxx) server_ssl.ehlo() # optional, called by login() server_ssl.login('xxxx@xxx.local', 'xx') # ssl server doesn't support or need tls, so don't call server_ssl.starttls() server_ssl.sendmail("xxx@xxx.com", "xxx@xxx.com", "hello") #server_ssl.quit() server_ssl.close() print 'successfully sent the mail' Error: Traceback (most recent call last): File "Script5.py", line 3, in <module> server_ssl = smtplib.SMTP_SSL('smtp.office365.com', xxx) File "C:\Python27\ArcGIS10.7\lib\smtplib.py", line 802, in __init__ SMTP.__init__(self, host, port, local_hostname, timeout) File "C:\Python27\ArcGIS10.7\lib\smtplib.py", line 259, in __init__ raise SMTPConnectError(code, msg) smtplib.SMTPConnectError: (-1, 'The Microsoft Exchange IMAP4 service is ready. [QgBOADYAUABSADEAMQBDAEEAMAAw]') Any help is appreciated. Thank you! #
... View more
08-05-2019
01:58 PM
|
0
|
1
|
3274
|
POST
|
Getting this error Traceback (most recent call last): File "C:/Users/user/Desktop/att.py", line 28, in <module> open(fileLocation + os.sep + origName + ".jpg", 'wb').write(binaryRep.tobytes()) IOError: [Errno 2] No such file or directory: u'C:/Users/user/pictures/pics/\\HGC-2.jpg' Any further suggestions?
... View more
06-14-2019
08:13 AM
|
0
|
1
|
658
|
POST
|
import arcpy from arcpy import da import os attachTable = 'C:\users\user\Test2\pictures.gdb\pictures__ATTACH' # Table in GDB holding attatchments origTable = 'C:\Users\user\Test2\pictures.gdb\pictures' # Layer in GDB holding features to which attatchments belong nameField = 'Name' # Field where you want to save the photos fileLocation = 'C:\Users\user\pictures\pics' # folder where you want to save the photos # creates a cursor to search through the attachment tables; specify yu only wish to search those three fields attachCursor = arcpy.da.SearchCursor(attachTable, ['DATA', 'ATT_NAME', 'REL_GLOBALID']) # Begin searching the table and storing the actual images, movies, etc. for attRow in attachCursor: binaryRep = attRow[0] filename = attRow[1] relID = attRow[2] # creates a cursor to sort the features; essentially to find a match fro the relID above originCursor = arcpy.da.SearchCursor(origTable, ['GLOBALID', nameField]) for origRow in originCursor: origID = origRow[0] origName = origRow[1] if origID == relID: break # Saves a file in the specified location tht contains the name chosen by the user for the attachment open(fileLocation + os.sep + origName + ".jpg", 'wb').write(binaryRep.tobytes()) # deletes search cursor del originCursor ERROR Traceback (most recent call last): File "C:/Users/mpretorius/Desktop/att.py", line 28, in <module> open(fileLocation + os.sep + origName + ".jpg", 'wb').write(binaryRep.tobytes()) IOError: [Errno 2] No such file or directory: u'C:\\Users\\user\\pictures\\pics\\HGC-2.jpg' Can't seem to figure out what is wrong in this script. Any help appreciated!
... View more
06-14-2019
07:34 AM
|
0
|
6
|
798
|
POST
|
I keep getting this error when trying to batch export KMZ's into a file geodatabase. There are KMZ in the environment so confused on the error. TypeError Traceback (most recent call last)<ipython-input-23-ee7602b7dcab> in <module>() 17 18 # Convert all KMZ and KML files found in the current workspace---> 19 for kmz in arcpy.ListFiles('*.KM*'): 20 print("CONVERTING: {0}".format(os.path.join(arcpy.env.workspace, kmz))) 21 arcpy.KMLToLayer_conversion(kmz, out_location)TypeError: 'NoneType' object is not iterable
... View more
02-08-2019
06:43 AM
|
0
|
1
|
508
|
POST
|
Is there a quick way to auto-name photo's in Collector with a entered attribute value?
... View more
01-15-2019
09:41 AM
|
0
|
0
|
215
|
DOC
|
Getting this error with enterprise. Anyone have a possible solution?
... View more
01-08-2019
01:26 PM
|
0
|
0
|
5935
|
POST
|
Hello, I am trying to run this script to export attachments to a folder and get the following error. Script is attached.
... View more
01-08-2019
01:07 PM
|
0
|
1
|
356
|
POST
|
I'm running Jupyter and trying to run this script to pull files from arcgis enterprise to a desktop folder and I am getting the following bolded error. What is needed to fix this? # Version 1.2 import logging, os, re, datetime from IPython.display import display from arcgis.gis import GIS (ModuleNotFoundError: No module named 'arcgis') ''' ********************** SCRIPT CONFIGURATION START ********************** ''' #What is the ID of the Feature Layer you want to download attachments from? FeatureLayerId = 'XXXX' #What are your ArcGIS Enterprise/ArcGIS Online credentials? This is case sensitive. PortalUserName = 'XXXX' PortalPassword = 'XXXX' PortalUrl = 'XXXX' #Where do you want your attachments stored? SaveAttachmentsTo = 'S:\GIS\Pictures' SaveLogsTo = 'Logging' #How do you want your attachments stored? Options are GroupedFolder and IndividualFolder #GroupedFolder - Attachments from every feature in each layer is stored in the same folder - attachments are renamed in the format OBJECTID-ATTACHMENTID-OriginalFileName #IndividualFolder - A new folder is created for each OBJECTID, and associated attachments are stored in that folder - attachments are renamed in the format ATTACHMENTID-OriginalFileName AttachmentStorage = 'GroupedFolder' #Set to False if ArcGIS Enterprise cert is not valid PortalCertVerification = True #Setup logging - levels are DEBUG,INFO,WARNING,ERROR,CRITICAL logging.basicConfig(level=logging.INFO) ''' ********************** SCRIPT CONFIGURATION END ********************** ''' #https://stackoverflow.com/questions/273192/how-can-i-create-a-directory-if-it-does-not-exist def createFolder(folderPath): if not os.path.exists(folderPath): try: os.makedirs(folderPath) except OSError as e: if e.errno != errno.EEXIST: raise def renameFile(currentAttachmentPath, newAttachmentPath): #Rename file - ensure new attachment path does not exist already if not os.path.exists(newAttachmentPath): os.rename(currentAttachmentPath, newAttachmentPath) logger.info('{} being renamed as {}'.format(currentAttachmentPath, newAttachmentPath)) else: logger.warning('Not able to rename {} as {} because file already exists. Removing {}'.format(currentAttachmentPath, newAttachmentPath, currentAttachmentPath)) os.remove(currentAttachmentPath) #Create specified folder if it does not exist already createFolder(SaveAttachmentsTo) createFolder(SaveLogsTo) #Logging level specified in script configuration logger = logging.getLogger(__name__) logFileName = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S') fileHandler = logging.handlers.RotatingFileHandler('{}/{}.log'.format(SaveLogsTo, logFileName), maxBytes=100000, backupCount=5) formatter = logging.Formatter('%(asctime)s %(levelname)s %(relativeCreated)d \n%(filename)s %(module)s %(funcName)s %(lineno)d \n%(message)s\n') fileHandler.setFormatter(formatter) logger.addHandler(fileHandler) logger.info('Script Starting at {}'.format(str(datetime.datetime.now()))) #Connect to GIS, and get Feature Layer information if PortalUserName == '' and PortalPassword == '': gis = GIS() else: gis = GIS(PortalUrl, PortalUserName, PortalPassword, verify_cert=PortalCertVerification) downloadCounter = 0 nonDownloadCounter = 0 downloadSizeCounter = 0 itemObject = gis.content.get(FeatureLayerId) logger.info('Iterating through layers in Feature Layer "{}"'.format(itemObject.name)) display(itemObject) #Loop through layers in Feature Layer for i in range(len(itemObject.layers)): featureLayer = itemObject.layers #Skip layer if attachments are not enabled if featureLayer.properties.hasAttachments == True: #Remove any characters from feature layer name that may cause problems and ensure it's unique... featureLayerName = '{}-{}'.format(str(i), re.sub(r'[^A-Za-z0-9]+', '', featureLayer.properties.name)) featureLayerFolder = SaveAttachmentsTo + r'\\' + featureLayerName createFolder(featureLayerFolder) #Query to get list of object ids in layer featureObjectIds = featureLayer.query(where='1=1', return_ids_only=True) #Provide some updates to user... logger.info('Time: {}'.format(str(datetime.datetime.now()))) logger.info('Currently looping through feature attachments in layer {} of {}: storing in folder named "{}"'.format(str(i + 1), str(len(itemObject.layers)), featureLayerName)) logger.info('There are {} features to iterate in this layer'.format(str(len(featureObjectIds['objectIds'])))) #Loop through features in layer emptyAttachments = 0 for j in range(len(featureObjectIds['objectIds'])): currentObjectId = featureObjectIds['objectIds'] currentObjectIdAttachments = featureLayer.attachments.get_list(oid=currentObjectId) if len(currentObjectIdAttachments) > 0: #Loop through feature attachments and download to appropriate folder for k in range(len(currentObjectIdAttachments)): attachmentId = currentObjectIdAttachments ['id'] attachmentName = currentObjectIdAttachments ['name'] attachmentSize = currentObjectIdAttachments ['size'] if AttachmentStorage == 'IndividualFolder': currentFolder = featureLayerFolder + r'\\' + str(currentObjectId) #Create a folder for attachments createFolder(currentFolder) fileName = '{}-{}'.format(attachmentId, attachmentName) newAttachmentPath = '{}\\{}'.format(currentFolder, fileName) if not os.path.isfile(newAttachmentPath): logger.info('The size of the current attachment being downloaded is {}MB'.format((attachmentSize/1000000))) currentAttachmentPath = featureLayer.attachments.download(oid=currentObjectId, attachment_id=attachmentId, save_path=currentFolder) #Rename to ensure file name is unique renameFile(currentAttachmentPath, newAttachmentPath) downloadCounter += 1 downloadSizeCounter += attachmentSize else: logger.info('File {} already exists. Not downloading again!'.format(newAttachmentPath)) nonDownloadCounter += 1 elif AttachmentStorage == 'GroupedFolder': fileName = '{}-{}-{}'.format(currentObjectId, attachmentId, attachmentName) newAttachmentPath = '{}\\{}'.format(featureLayerFolder, fileName) if not os.path.isfile(newAttachmentPath): logger.info('The size of the current attachment being downloaded is {}MB'.format((attachmentSize/1000000))) currentAttachmentPath = featureLayer.attachments.download(oid=currentObjectId, attachment_id=attachmentId, save_path=featureLayerFolder) #Rename to ensure file name is unique renameFile(currentAttachmentPath, newAttachmentPath) downloadCounter += 1 downloadSizeCounter += attachmentSize else: logger.info('File {} already exists. Not downloading again!'.format(newAttachmentPath)) nonDownloadCounter += 1 else: logger.error('AttachmentStorage option not valid: {}. Valid options are IndividualFolder and GroupedFolder'.format(AttachmentStorage)) else: emptyAttachments += 1 logger.info('{} of these features do not contain attachments'.format(str(emptyAttachments))) else: logger.info('Layer {} does not have attachments enabled'.format(featureLayer.properties.name)) logger.info('Summary: {} new files have been downloaded totalling {}MB in size'.format(downloadCounter, (downloadSizeCounter/1000000))) logger.info('Summary: {} attachments already existed so were not downloaded again'.format(nonDownloadCounter))
... View more
01-08-2019
08:52 AM
|
0
|
2
|
1327
|
Title | Kudos | Posted |
---|---|---|
1 | 01-08-2019 11:25 AM | |
1 | 02-08-2019 06:58 AM |
Online Status |
Offline
|
Date Last Visited |
11-11-2020
02:25 AM
|