Search code examples
pythonrarcpyreticulate

Importing arcpy with reticulate


I wish to import the arcpy library in R using reticulate.

I tried running this code in R:

library(reticulate)
use_python("C:/Python27/ArcGIS10.4")
arcpy = import("arcpy")

This gives me an error:

Error in py_module_import(module, convert = convert) : 
  object 'arcpy' not found

I'm not entirely sure how Python goes about finding its modules (apparently it searches PYTHONPATH, but I don't know where this is defined).

I do understand that the arcpy library is actually in a different folder. Doing a bit of digging, I think I found it, so I tried this in R:

arcpy = import_from_path("arcpy", path = "C:/Program Files (x86)/ArcGIS/Desktop10.4/ArcPy/arcpy")

But got the following error:

Error in py_module_import(module, convert = convert) : 
  ImportError: cannot import name 'gp'

Detailed traceback: 
  File "C:/Program Files (x86)/ArcGIS/Desktop10.4/ArcPy\arcpy\__init__.py", line 22, in <module>
    from arcpy.geoprocessing import gp

So I'm not too sure what's going on here, but I get the impression it has to do with Python or reticulate not looking in the right place for the right files?


Solution

  • Try adding the full path to the Python.exe file within C:/Python27/ArcGIS10.4. In addition, use required = TRUE, so reticulate know that it has to use the provided python version.

    If it resides directly in that folder, then

    library(reticulate)
    
    use_python("C:/Python27/ArcGIS10.4/Python.exe", required = TRUE)
    
    arcpy <- import("arcpy")