In my last post I went over installing and setting up a Python virtual environment. Now I want to make it work with a specific library in my existing Python installation - Esri's Arcpy.
This is useful as it enables you to access other libraries without having to install them in the virtual environment. As I am learning OpenCV for example, I want to test if I can incorporate any spatial tools in the processing steps. Rather than installing arcpy in the virtual environment, I can simply set it up to be able to access my existing install, then I can just call import arcpy directly.
This could also be useful for GDAL or QGIS tools, or any other libraries you have already installed.
The USGS has a very good write up on calling
arcpy from virtual environments.
To summarize:
To use arcpy in your virtual environment, you don't want to copy all the ESRI stuff in, you just want to tell it where to find the ArcGIS installed components.
To do this,
you'll need to place a *.pth file in the Lib\site-packages subdirectory of your virtual environment. If you used the WORKON_HOME variable from the last post, in Windows this defaults to %USERPROFILE%Env.
You can call this file whatever you want, something like "arcgis_arcpy.pth" works.
You can call this file whatever you want, something like "arcgis_arcpy.pth" works.
In the file, you'll need to put all the directories
that ArcGIS uses to make arcpy work. The easiest way to get this list
of pathnames is to start ArcMap, start the python window, type
import sys
then
sys.path
and
copy the list into a text file. Save this as a '.pth' file. Note that the file should look something like
the following (text after a # are comments and will not be read).# Place in your virtual environment folder ...\\lib\site-packages\
C:\\Windows\\system32
C:\\Windows\\system32\\python27.zip
# Esri specific for arcpy - Note 10.3 specific
C:\\Program Files (x86)\\ArcGIS\\Desktop10.3\\bin
C:\\Program Files (x86)\\ArcGIS\\Desktop10.3\\arcpy
C:\\Program Files (x86)\\ArcGIS\\Desktop10.3\\ArcToolbox\\Scripts
C:\\Python27\\ArcGIS10.3
C:\\Python27\\ArcGIS10.3\\Lib
C:\\Python27\\ArcGIS10.3\\DLLs
C:\\Python27\\ArcGIS10.3\\Lib\\lib-tk
C:\\Python27\\ArcGIS10.3\\lib\\site-packages