Search code examples
rbatch-fileshell-exec

Problems executing a batch file from R


I am creating a function in R and in one step of the function I run a batch file, this batch file in turn runs a different program which creates files that I then want to read in my function.

I am using shell.exec to run the batch file and it runs fine, the problem is that the next line of my code that wants to read in the output from the program ran by the batch file crashes because it hasn't been created yet.

So I get an error the first time I call my function but if I simply call it again it runs fine. Example of code below: Basically what happens is I get an error message when calling the function saying that .../bat_output.txt does not exist, because the batch file hasn't been run yet, but then when I call the function again, it works fine.

shell.exec("run.bat")
readout<-read.table("bat_output.txt")

Any suggestions?


Solution

  • shell.exec returns immediately while the script is running in the background. The reason bat_output.txt is not found the first time is likely that the script has not finished yet. shell.exec does not give you the ability to wait or any information to determine if the process is still running, so it might not be the best tool for this.

    Alternatives:

    system("cmd /c run.bat")
    system2("cmd", c("/c", "run.bat"))
    

    Realize that if you reference a different path, you might want/need to normalizePath and/or dQuote it going into those commands. (R's system* commands are bad at argument forming.)