Search code examples
pythonrsystemwhitespaceargument-passing

In R: use system() to pass python command with white spaces


Im trying to pass a python command from R (on Windows x64 Rstudio) to a python script via the command promt. It works if I type directly into cdm but not if I do it via R using the R function system(). The format is (this is how I EXACTLY would write in the windows cmd shell/promt):

pyhton C:/some/path/script <C:/some/input.file> C:/some/output.file

This works in the cmd promt, and runs the script with the input file (in <>) and gives the output file. I thought I in R could do:

system('pyhton C:/some/path/script <C:/some/input.file> C:/some/output.file')

But this gives an error from python about

error: unparsable arguments: ['<C:/some/input.file>', 'C:/some/output.file']

It seems as if R or windows interpret the white spaces different than if I simply wrote (or copy-paste) the line to the cmd promt. How to do this.


Solution

  • From ?system

    This interface has become rather complicated over the years: see system2 for a more portable and flexible interface which is recommended for new code.

    System2 accepts a parameter args for the arguments of your command.

    So you can try:

    system2('python', c('C:\\some\\path\\script', 'C:\\some\\input.file', 'C:\\some\\output.file'))
    

    On Windows:

    R documentation is not really clear on this point (or maybe it's just me), anyway it seems that on Windows the suggested approach is to use the shell() which is less raw than system and system2, plus it seems to work better with redirection operators (like < or >).

    shell ('python C:\\some\\path\\script < C:\\some\\input.file > C:\\some\\output.file')
    

    So what is this command doing is:

    1. Call python
    2. Telling python to execute the script C:\some\path\script. Here we need to escape the '\' using '\'.
    3. Then we passing some inputs to the script using a the '<' operator and the input.file
    4. We redirect the output (using '>') to the output file.