running .exe from R: status 127 warning on Linux not on Windows - r

I'm calling an .exe from R using system("script.exe object").
I get Warning: running command had status 127. I know it means the .exe file has not been found.
I'm on windows. When I use shell instead of system it works like a charm. However, I am designing a Shiny application that will be deployed in a Linux environment (shinyapps.io). This is why I need to use system.
EDIT
On Windows, it works with system(paste("cmd.exe /c", "script.exe object"), intern = FALSE, wait = TRUE) as suggested here. But not when I deploy the app (on Linux).
HINT
Locally on Windows, if I replace system with system2: system2(paste("cmd.exe /c", "script.exe object"), wait = TRUE), it raises the status 127 warning and the output is exactly the same as in my deployed app on Linux.
It's tough to create a reproducible example here but if needed I can try. Please tell me.
Context: basically the .exe is a black box (compiled C++ code) that takes a .txt file as input and outputs another .txt file. I am using R to dump the .txt file to the current working directory, then read back in the .txt file generated by the .exe (created in the current working directory, where the .exe file is stored).

Just add \" could solve you problem, e.g.
> setwd("W:/www/ADemo/")
> system(paste0(getwd(),"/Hi 2.exe"))
Hello, world.
> setwd("W:/www/A Demo/")
> system(paste0(getwd(),"/Hi 2.exe"))
Warning message:
running command 'W:/www/A Demo/Hi 2.exe' had status 127
> system(paste0("\"",getwd(),"/Hi 2.exe","\" "))
Hello, world.
Update:
The 127 error is usually seen when there is a space in the path. One also needs to worry about the input of the application, e.g. "/path A/A 2" --in-path "/home/A/B C/d 123.dta". Here are some update comments:
system(shQuote(paste0(getwd(),"/Hi 2.exe"))) is much more convenient.
At least in R 3.2.4, the manual of system() recommends to use system2() instead to avoid path problem under Win/Linux/OSX/.
Update 2:
For Linux user, I created a function to detect the given file in your working directory is executable or not:
chkpermission<-function(file, mode='0777'){
exe_list <- system("echo `ls -l | grep -E ^-.{2}x\\|^-.{5}x\\|^-.{8}x` | awk '{print $9}'", intern=T)
if(length(exe_list)==0){
stop("no file is executable");
##Make sure you know what you are doing here, add a+x permission:
## if (!(file%in%exe_list)) Sys.chmod(file, mode = mode)
}
return(file%in%exe_list);
}
I've tested it on GNU awk/grep. The 2/5/8 indicates the executable permission of [u/2]ser, [g/5]roup, [o/8]thers., one could change it to meet the requirement.

The problem actually stemmed from the fact that .exe files are executables for Windows only. It does not work out of the box on Linux environments (you can use WINE but in my case it is not possible because I am calling the executable from within R, I don't have any sudo rights or anything on the virtual machine used by the host of my app). So I compiled the c++ code I had using g++ on a Linux virtual machine and used the .out file rather than the .exe.
Then in my R script I just needed these two calls:
system("chmod a+x script.out") # to make Linux understand that the file is an executable
system("./script.out object") # to run the script

Related

Error that says Rscript is not recognized as an internal or external command, operable program or batch file [duplicate]

shell_exec("Rscript C:\R\R-3.2.2\bin\code.R ");
This is the call to script.On calling the above script, the error occurs.
I am trying to call my R script from the above path but no output is being shown. While checking the error logs of PHP, it says 'Rscript' is not recognized as an internal or external command, operable program or batch file.' The script is working fine on the Rstudio but not running on the command line.
Add the Rscript path to your environment variables in Windows:
Go to Control Panel\System and Security\System and click Advanced System Settings, then environment variables, click on path in the lower box, edit, add "C:\R\R-3.2.2\bin"
Restart everything. Should be good to go. Then you should be able to do
exec('Rscript PATH/TO/my_code.R')
instead of typing the full path to Rscript. Won't need the path to your my_code.R script if your php file is in the same directory.
You need to set the proper path where your RScript.exe program is located.
exec ("\"C:\\R\\R-3.2.2\\bin\\Rscript.exe\"
C:\\My_work\\R_scripts\\my_code.R my_args";
#my_args only needed if you script take `args`as input to run
other way is you declare header in your r script (my_code.r)
#!/usr/bin/Rscript
and call it from command line
./my_code.r
If you are running it in Git Bash terminal, you could follow a revised version of the idea suggested by #user5249203: in the first line of your file my_code.R, type the following
#!/c/R/R-3.2.2/bin/Rscript.exe
I assumed that your path to Rscript.exe is the one listed above C:\R\R-3.2.2\bin. For anyone having a different path to Rscript.exe in Windows, just modify the path-to-Rscript accordingly. After this modification of your R code, you could run it in the Git Bash terminal using path-to-the-code/mycode.R. I have tested it on my pc.
I faced the same problem while using r the first time in VS Code, just after installing the language package (CRAN).
I restart the application and everything worked perfectly. I think restarting would work for you as well.

How to import data file for a Windows executable file from R?

I am trying to run a Windows executable file from R. I have managed to open the executable file from R using the command:
system2('cmd', args=c('/c', '"C:/Program Files (x86)/UIFormModel.exe"'))
To run the executable file, I need to import an Excel file by clicking on the button “Load Settings File” (see figure below). Thus, the button is part of the executable file.
How can I do this from R ?
I have tried this command but it does not work:
system2('cmd', args=c('/c', '"C:/Program Files (x86)/UIFormModel.exe"', '"F:/template_LHS1.xlsx"'))
'C:/Program' is not recognized as an internal or external command,
operable program or batch file.
Warning message:
running command '"cmd" /c "C:/Program Files (x86)/UIFormModel.exe" "F:/template_LHS1.xlsx"' had status 1
Several points:
normally one does not have .exe files directly under C:\Program Files (X86) so first double check the path name. I suspect it is not as in the question but is something like the one shown below.
note the quoting used below
are you sure that the program accepts a command line argument as an alternative to its GUI? Can you run it from Windows cmd line? If not you could write an autohotkey (see AutoHotKey section below) or autoit script to control it and launch that from R.
if it does accept an argument ensure that the program allows forward slashes -- if not use backslashes
cmd line argument accepted
If the program accepts a command line argument then try this code:
system2("C:/Program Files (x86)/UIFormModel/UIFormModel.exe", "F:/template_LHS1.xlsx")
Another way is:
shell('"C:/Program Files (x86)/UIFormModel/UIFormModel.exe" F:/template_LHS1.xlsx')
For example, using the free CSVfix I was able to run the following and found that they worked:
system2("C:/Program Files (x86)/CSVfix/CSVfix.exe", "help")
shell('"C:/Program Files (x86)/CSVfix/CSVfix.exe" help')
See ?system2 and ?shell for other arguments you may wish to use.
AutoHotKey
If the program does not accept command line arguments then this sample AutoHotKey script launches WinMerge, a free file comparison GUI for Windows, comparing the WinMerge executable to itself. This has the effect of generating a popup warning and the AutoHotKey script dismisses that warning message by sending an Enter keystroke to the WinMerge window.
Be sure AutoHotKey and WinMerge are installed, that the script below is in a text file, test.ahk, in the current directory, the one given by getwd(), and then from the R console run:
shell("test.ahk")
Here is the test.ahk script:
exe = "C:\Program Files (x86)\winmerge\winmergeu.exe"
Run %exe% %exe% %exe%
WinWait WinMerge
; dismiss the dialog warning that both files are the same
Send {Enter}
If you go this route this script will need to be modified or rewritten in ways that will be specific to your program.
I've been trying several alternatives, but I've not successfully called an executable with a parameter. Nevertheless I can suggest a workaround using a .bat file:
system2("cmd.exe", input='"D:/workspace/execute.bat"')
Where execute.bat may contain something like:
C:/Program Files (x86)/UIFormModel.exe F:/template_LHS1.xlsx

Trouble with path specifications when running RStudio from a console

I have R script within a plain text file named "TestFile.R".
I am running RStudio. I want to use the Windows console (cmd.exe) to pipe "TestFile.R" directly into the "R Script" editor of RStudio, without launching a new thread of RStudio.
This command in the console does exactly what I want:
rstudio -f TestFile.R
The contents of "TestFile.R" go straight into the RScript editor of the existing thread of RStudio.
It assumes, however, that "TestFile.R" is in the "bin" folder of RStudio, and also that
cmd.exe is running within that folder.
But I want to be able to do this from anywhere on my computer, using a console command like:
pathToRstudio\rstudio -f pathToTestFile\TestFile.R
To give an example, on my computer, this command fails:
C:\"Statistical packages"\RStudio\bin\rstudio -f E:\"my project"\TestFile.R
By trial and error, I discovered these solutions:
1/ omit the "C:\" part
2/ avoid quotation marks in the pathToTestFile.
So this console command works fine:
"Statistical packages"\RStudio\bin\rstudio -f E:\myproject\TestFile.R
Of course, I still am very restricted ; my default folder has to be "C:\", and I cannot have spaces in the path to TestFile.R, even though spaces within the Rstudio path are apparently OK !?
Could somebody please explain to me how to write this command in a way that is completely generic with regard to path specification?
I want to be able to run it from any folder, and have TestFile.R in any other folder. I do not want hassles about folder names containing spaces.

Unable to run R script through .bat files in Windows Server

I'm trying to run a R script through a .bat file. When I run myself the commands line by line it works. But when I try to run the .bat file, it doesn't works.
This is the .bat file
cd "C:\Program Files\R\R-3.1.2\bin"
R CMD BATCH "C:\Users\Administrator\Downloads\testa_vps.R"
This is the R script
setwd('C:\Users\Administrator\Documents')
file.create('mycsv.csv')
I'm not an expert with Windows and generally try to stick to Unix-like systems for things like this, but I have found that using programs non-interactively (e.g. via .bat files) is usually less error-prone when you add the appropriate directories to your (user) PATH variable, rather than cding into the directory and calling the executable from within the .bat file. For example, among other things, my user PATH variable contains C:\PROGRA~1\R\R-3.0\bin\; - the directory that contains both R.exe and Rscript.exe - (where PROGRA~1 is an alias for Program Files which you can use in an unquoted file path, since there are no spaces in the name).
After you do this, you can check that your PATH modification was successful by typing Rscript in a new Command Prompt - it should print out usage information for Rscript rather than the typical xxx is not recognized as an internal or external command... error message.
In the directory C:\Users\russe_000\Desktop\Tempfiles, I created test_r_script.r, which contains
library(methods)
setwd("C:\Users\russe_000\Desktop\Tempfiles")
file.create("mycsv.csv")
and test_r.bat, which contains
Rscript --vanilla --no-save "C:\Users\russe_000\Desktop\Tempfiles\test_r_script.r"
Clicking on the Windows Batch File test_r ran the process successfully and produced mycsv.csv in the correct folder.
Before running test_r.bat:
After running test_r.bat:
I've never worked with a Windows server, but I don't see why the process would be fundamentally different than on a personal computer; you just may need your sysadmin to modify the PATH variable if you don't have sufficient privileges to alter environment variables.
As already suggested by #nrussel in the comments you should use RScript.exe for this.
Create a file launcher.bat with the following content:
cd C:\Users\Administrator\Documents
Rscript testa_vps.R
In addition, add C:\Program Files\R\R-[your R version]\bin\x64; or C:\Program Files\R\R-[your R version]\bin\i386to the System PATH variable in the Environment Variables menu depending if you run R on a 64-bit or 32-bit system.
I just tested the approach above successfully on a Windows Server 2008 64-bit system and mycsv.csv got created as expected.
EDIT
One important point I forgot to mention is the following: You need to specify the path in your R file in the setwd() call using \\ instead of \.
setwd('C:\\Users\\Administrator\\Documents')
Here is a screenshot of the successful run on the Windows 2008 server:
Note: I added cmd /k to the .bat file so that the cmd window stays open after clicking on the file.

How to remove files from a Windows folder using the shell() command

I have s script that produces a lot of small PNG files that I want to remove when I close my gWidgets interface. I thought I could do that in Windows using
shell( "del *.png" )
but neither in the script nor in interactive mode in R (2.15.2), this has any effect at all (not even an error or warning). Probably I'm doing something wrong but I can't find out so far what.
Has somebody an idea for me?
I've just tested your command -- same version of R on Windows XP -- and it works exactly as you would expect. If this command is not working for you, I strongly suspect that R's working directory may be different from the directory in which you have your .png files.
You could try:
shell('dir *.png')
... to verify that the .png files are, in fact, in the current working directory before trying to delete them. If they are not there, you will get the report:
File Not Found
Warning messages:
1: running command 'C:\WINDOWS\system32\cmd.exe /c dir *.png' had status 1
2: In shell("dir *.png") : 'dir *.png' execution failed with error code 1
Also, if you've run the del command once, so there are no .png files remaining in the directory, the second time that you run that command you should get an error message like the following:
> shell("del *.png")
Could Not Find C:\usr\sjl\dev\test\R\*.png

Resources