call python with system() in R to run a python script emulating the python console

后端 未结 3 1548
感情败类
感情败类 2020-12-31 11:19

I want to pass a chunk of Python code to Python in R with something like system(\'python ...\'), and I\'m wondering if there is an easy way to emulate the pytho

3条回答
  •  鱼传尺愫
    2020-12-31 11:57

    My work around for this problem is defining my own functions that paste in parameters, write out a temporary .py file, and them execute the python file via a system call. Here is an example that calls ArcGIS's Euclidean Distance function:

    py.EucDistance = function(poly_path,poly_name,snap_raster,out_raster_path_name,maximum_distance,mask){
    
        py_path = 'G:/Faculty/Mann/EucDistance_temp.py'
        poly_path_name = paste(poly_path,poly_name, sep='')
    
        fileConn<-file(paste(py_path))
        writeLines(c(
            paste('import arcpy'),
            paste('from arcpy import env'),
            paste('from arcpy.sa import *'),
            paste('arcpy.CheckOutExtension("spatial")'),
    
            paste('out_raster_path_name = "',out_raster_path_name,'"',sep=""),
            paste('snap_raster = "',snap_raster,'"',sep=""),
            paste('cellsize =arcpy.GetRasterProperties_management(snap_raster,"CELLSIZEX")'),
            paste('mask = "',mask,'"',sep=""),
            paste('maximum_distance = "',maximum_distance,'"',sep=""),
            paste('sr = arcpy.Describe(snap_raster).spatialReference'),
    
            paste('arcpy.env.overwriteOutput = True'),
            paste('arcpy.env.snapRaster = "',snap_raster,'"',sep=""),
            paste('arcpy.env.mask = mask'),
            paste('arcpy.env.scratchWorkspace ="G:/Faculty/Mann/Historic_BCM/Aggregated1080/Scratch.gdb"'),
            paste('arcpy.env.outputCoordinateSystem = sr'),
    
    
            # get spatial reference for raster and force output to that
            paste('sr = arcpy.Describe(snap_raster).spatialReference'),
            paste('py_projection = sr.exportToString()'),     
            paste('arcpy.env.extent = snap_raster'),
            paste('poly_name = "',poly_name,'"',sep=""),
            paste('poly_path_name = "',poly_path_name,'"',sep=""),
    
            paste('holder = EucDistance(poly_path_name, maximum_distance, cellsize, "")'),
            paste('holder = SetNull(holder < -9999, holder)'),
            paste('holder.save(out_raster_path_name) ')
    
        ), fileConn, sep = "\n")
        close(fileConn)
    
        system(paste('C:\\Python27\\ArcGIS10.1\\python.exe', py_path))
    }
    

提交回复
热议问题