[GIS] Python Crashes when Running ArcPy’s ExportToPDF(), ExportToPNG(), ExportToJPEG()

.jpgarcpyexportpdfpng

I am attempting to loop through a folder of ~400 .mxd's and save each to a .pdf in another folder. All tested arcpy.mapping export functions (pdf, jpeg & png) kill python without a chance to debug or any indication why. Running script in PythonWin gives error message "PyWin32 has stopped working." When run from python prompt within ArcMap, program just closes.

Script behaves inconsistently, sometimes makes 10 maps before crashing, other times only 1 or 2. All mxds were created from the same arcpy.mapping script and all are valid (can open in ArcMap and export without issues). There is an ArcGIS Online basemap layer in each map (Oceans), I tried unchecking this layer in the first few maps and it did not have an effect on the script, python still crashed.

Tested script on 2 different laptops with same result. Both running ArcGIS Desktop 10.2.2, Python 2.7…

Windows 7 Pro 64-Bit SP1, Intel Core i5, 8GB Dual-Channel RAM, Intel HD Graphics 4000

Windows 7 Pro 64-Bit SP1, Intel Core i7, 16GB Dual-Channel RAM, Intel HD Graphics 4000, 2048MB NVIDIA Quatro K2000M

Saw a few similar posts here and on other message boards, but no working solutions.

I had no problem generating 400 maps using arcpy.mapping and cannot believe that I cannot save them out to a file. Is this a bug?

import arcpy, os  

ws = r"C:\temp"  
map_folder = os.path.join(ws, "maps")  
pdf_folder = os.path.join(ws, "pdfs")  

arcpy.env.workspace = map_folder  
arcpy.env.overwriteOutput = True  

# generate list of map documents in folder to loop through  
map_list = arcpy.ListFiles("*.mxd")  

###     
def exportAISMap(mxd_path, out_path):  
    mxd = arcpy.mapping.MapDocument(mxd_path)  
    # arcpy.mapping.ExportToJPEG(mxd, out_path)  
    # arcpy.mapping.ExportToPNG(mxd, out_path)  
    arcpy.mapping.ExportToPDF(mxd, out_path)  
    print "Exported map file: " + str(out_path) + "\n"  
    # mxd.save()  
    del mxd  
###  

print "Saving out " + str(len(map_list)) + " map documents\n"     

for map_file in map_list:  
    print map_file  

    mxd_path = os.path.join(map_folder, map_file)  

    pdf_file = map_file.replace(".mxd", ".pdf")  
    pdf_path = os.path.join(pdf_folder, pdf_file)     

    exportAISMap(mxd_path, pdf_path)  

Best Answer

i don't trust the gc module as much as I do spawning a separate process. The separate process will do the work and will then be killed after the join(). Try adding:

from multiprocessing import process

to the top of your script then replace:

exportAISMap(mxd_path, pdf_path)

with

p = Process(target = exportAISMap, args = (mxd_path, pdf_path))
p.start()
p.join()
Related Question