Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I have a python script that I am using to create a list of all mxd files (with full pathing) in our Projects folder. The script then uses that to iterate through the list and do a findandreplaceworkspacepaths on each mxd per ESRI's how to. I am running into problems when I hit a corrupted mxd file. The have tried try/except and haven't gotten it to work. The ideal situation would be to write the corrupt filename to a file and move on so I can come back to them at the end. I'm very new with python scripting, any help would be greatly appreciated.

import arcpy, os, sys, traceback, time

oldpath = 'W:'
newpath = 'W:\\GIS'

def find(path,pattern):
    matches = []
    for r,d,f in os.walk(path):
        for files in f:
            if files.endswith(pattern):
                fpath = os.path.join(r,files)
                matches.append(fpath)
                print (fpath)
    return matches


print ("Go: ")
mxdlist = (find('C:\\gis','.mxd'))
print (mxdlist)


print ("Starting Path Conversion")
try:
        for mxdold in mxdlist:
            mxd = arcpy.mapping.MapDocument(mxdold)
            mxd.findAndReplaceWorkspacePaths(oldpath, newpath)
            time.sleep(6)
            mxd.save()
            time.sleep(6)
            print (mxdold)
            del mxd
    except arcpy.ExecuteError:    
        arcpy.AddError(arcpy.GetMessages(2))    

    except:    
        arcpy.AddError("Non-tool error occurred")
share|improve this question
add comment

2 Answers

First thing to do is bring the top of your for loop outside the try statement. You want to get into your iteration before you give the try statement a chance to kill your operation. Next you'll want to add a few lines to open an error log and write filenames of corrupt files.

import arcpy, os, sys, traceback, time

oldpath = 'W:\\'
newpath = 'W:\\GIS'
cgis_dir = 'C:\\gis'

mxdlist = []

print 'Go: '
files = os.listdir(cgis_dir)
for file in files:
    try:
        if file.split('.')[1] == 'mxd':
            mxdlist.append(file)
            print cgis_dir,file
    except:
        pass


print ("Starting Path Conversion")

for mxdold in mxdlist:
    try:
        mxd = arcpy.mapping.MapDocument(mxdold)
        mxd.findAndReplaceWorkspacePaths(oldpath, newpath)
        time.sleep(6)
        mxd.save()
        time.sleep(6)
        print (mxdold)
        del mxd
    except arcpy.ExecuteError:    
        arcpy.AddError(arcpy.GetMessages(2))
        f=open(r'W:\GIS\error.log','a')
        f.write(mxdold,'\n')
        f.close()

    except:    
        arcpy.AddError("Non-tool error occurred")
share|improve this answer
2  
+1 Nice one, beat me to it! However, don't open the log file with 'w'(rite) - use 'a'(ppend) instead as if there's more than one corrupt mxd you'll overwrite each time. Also, it may be overkill, but the Python logging module might be worth looking at to record errors. –  om_henners Feb 27 '12 at 14:04
    
Nice catch... fixed the code to open the file with 'a' to append. –  Jason Feb 27 '12 at 14:26
    
It is still failing with the modified code. I have verified that the files are not corrupt but I get it where Windows 7 claims it to have hung and kills the script. Any ideas? –  bworthington Feb 27 '12 at 14:56
    
What is the error you are getting? Can you post the rest of the code? –  Jason Feb 27 '12 at 15:29
1  
I have 2 suggestions: 1. Don't reinvent logging and log files. I've got a little Python logging howto at sgillies.net/blog/832/python-logging that has other good links. 2. Consider ditching the call to arcpy.AddError since you're writing your own handler action. –  sgillies Feb 27 '12 at 16:32
show 3 more comments

This has nothing to do with your error on the corrupt MXDs, but since you are wanting to log, here is a little bare-bones nugget (pretty much straight from the Python docs) using the logging module (as suggested by @om_henners). @sgillies comment above looks excellent as well.

import logging
import datetime
import os

date_tag = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
log_file = os.path.join(os.path.dirname(os.curdir), "LogFileTest_%s.log" % date_tag)

# Setup logger
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)-8s %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S',
                    filename=log_file,
                    filemode='w')
logging.info(': START LOGGING')

try:
    logging.info(": Do something here")
except Exception, err:
    logging.error(": %s" % str(err))

When run as-is, it gives:

enter image description here

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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