Skip to content

Instantly share code, notes, and snippets.

@dblanchardDev
Created February 2, 2022 20:14
Show Gist options
  • Save dblanchardDev/ff9eb39956b3ebc50a31bc573a1908e3 to your computer and use it in GitHub Desktop.
Save dblanchardDev/ff9eb39956b3ebc50a31bc573a1908e3 to your computer and use it in GitHub Desktop.
Repair paths used for Python imports and ArcPy DLLs before importing ArcPy. Fixes issues where ArcPy in Python 2.7 is used to call a Python 3 script with ArcPy.
import sys, os
# FIX PATHS FOR IMPORTS & DLL WHEN RUNNING ON SERVER
# (otherwise, it will try to load ArcPy from the Python 2.7 libraries when called via ArcGIS Server)
if ("\\Server\\framework\\runtime\\" in sys.executable):
# Get installation base (e.g. C:\Program Files\ArcGIS)
base = sys.executable.rsplit("\\Server\\", 1)[0]
baseLower = base.lower()
# Remove invalid python import paths
for p in sys.path.copy():
pl = p.lower()
if pl.startswith(baseLower) and not "\\framework\\runtime\\" in pl:
sys.path.remove(p)
if "\\desktop10." in pl:
sys.path.remove(p)
# Correct DLL Loading Paths
try:
import win32api
except ModuleNotFoundError:
message = "Required module pywin32 not found. Install on server using following command: \""
pipPath = os.path.join(os.path.dirname(sys.executable), "Scripts\pip")
printOutput(None, message + pipPath + "\" install pywin32", None)
exit()
win32api.SetDllDirectory(os.path.join(base, "Server\\bin"))
win32api.SetDllDirectory(os.path.join(base, "Server\\framework\\runtime\\ArcGIS\\bin"))
win32api.SetDllDirectory(os.path.join(base, "Server\\framework\\runtime\\ArcGIS\\bin\\Python\\envs\\arcgispro-py3"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment