How to find correct executable with Sys.which on Windows

后端 未结 2 1505
陌清茗
陌清茗 2020-12-11 05:58

What are the workarounds on Windows to make it so Sys.which finds the proper executables? Two cases that are reoccuring problems:

  1. convert.exe

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-11 06:12

    I asked a +/- identical question earlier this year over on R-devel. Among the replies was this one, by Henrik Bengtsson, who kindly provided the following useful function:

    Sys.which2 <- function(cmd) {
        stopifnot(length(cmd) == 1)
        if (.Platform$OS.type == "windows") {
            suppressWarnings({
                pathname <- shell(sprintf("where %s 2> NUL", cmd), intern=TRUE)[1]
            })
            if (!is.na(pathname)) return(setNames(pathname, cmd))
        }
        Sys.which(cmd)
    }
    
    ## Trying out Sys.which & Sys.which2 on my Windows box gives the following:
    Sys.which("convert")
    #                              convert 
    # "C:\\Windows\\system32\\convert.exe" 
    Sys.which2("convert")
    #                                                 convert 
    # "C:\\Program Files\\ImageMagick-6.8.8-Q16\\convert.exe" 
    

    I'm really not sure why R-core don't just fix Sys.which() to make it actually portable, but they at least do document root cause of this behavior in ?system (whose functionality is afflicted by the same problem):

    The search path for 'command' may be system-dependent: it will include the R 'bin' directory, the working directory and the Windows system directories before 'PATH'.

提交回复
热议问题