My aim is to invoke a python model using this shell. Is there a way to make a wrapper R file to execute this sh file?
My aim is to invoke a python model using this shell. Is there a way to make a wrapper R file to execute this sh file?
The recommended way to run a OS command is function system2.
system2("sh", args = "model.sh")
If the file model.sh is in the home directory and its contents are as below:
# file: model.sh
pwd
cd $1
pwd
cd $2
pwd
cd ~
the command "sh" followed by all arguments, the script name and its arguments, will change directory twice and then change back to the home directory "~".
system2(command = "sh", args = c("model.sh", "tmp", "tmp"))
#/home/rui
#/home/rui/tmp
#/home/rui/tmp/tmp
getwd()
#[1] "/home/rui"
If the script is to be made an executable, which can be done from an R command line
system2(command = "chmod", args = c("+x", "model.sh"))
then the first argument to system2 is the command (the script file) and the script's arguments are passed on in args.
system2(command = "./model.sh", args = c("tmp", "tmp"))
#/home/rui
#/home/rui/tmp
#/home/rui/tmp/tmp
getwd()
#[1] "/home/rui"
Return to previous permissions.
system2(command = "chmod", args = "-x model.sh")
Any system command can be run like this, see help("system2").
The vector of arguments can be a single character string like the last chmod command above or a vector with each argument in order.
system2("chmod", args = c("-x", "model.sh"))
In this case, the return value of system2 is the OS command error code.
res <- system2(command = "ls", args = c("-l", "model.sh"))
#-rwxrwxr-x 1 rui rui 45 fev 7 07:24 model.sh
res
#[1] 0
To have the command return a character vector of its output, set stdout = TRUE.
system2(command = "chmod", args = c("+x", "model.sh"))
main_sh <- system2(command = "./model.sh",
args = c("model.py","x.json"),
stdout = TRUE
)
See the help page section Value for further details on the return value.