[Rd] Possibly broken system2 env-option

Gábor Csárdi c@@rd|@g@bor @end|ng |rom gm@||@com
Tue Mar 19 11:51:10 CET 2019


Right. I suppose, one thing you can do is setting the env var in the
current process, call system2() and then unset/restore the env var.
This is unlikely to cause problems, unless your R process is
multi-threaded, and the env var causes troubles in the other threads.
The withr package makes setting the temporary env var convenient, but
it is easy to write your own with_envvar() function:

withr::with_envvar(
  c(VAR = "Hello world"),
  system2("sh", "-c 'echo $VAR'"))

This seems to be portable, at least it works on macOS and Windows.

G.


On Tue, Mar 19, 2019 at 10:44 AM peter dalgaard <pdalgd using gmail.com> wrote:
>
>      On Windows, ‘env’ is only supported for commands such as ‘R’ and
>      ‘make’ which accept environment variables on their command line.
>
> So I suppose that would be tricky.
>
> The basic issue is that on Unix-alikes, system2 constructs a command like
>
> FOO=bar cmd args
>
> and passes that to sh via system(). On windoes, system() does not call sh, so system2() does (effectively)
>
> cmd FOO=bar args
>
> and hopes that cmd knows what to do with the env setting.
>
> -pd
>
> > On 19 Mar 2019, at 11:09 , Gábor Csárdi <csardi.gabor using gmail.com> wrote:
> >
> > On Tue, Mar 19, 2019 at 9:59 AM peter dalgaard <pdalgd using gmail.com> wrote:
> > [...]
> >> What you need is something like (NB: single quotes!)
> >>> system2("sh", env = c("VAR='Hello World'"), args = c("-c 'echo $VAR'"))
> >> Hello World
> >
> > Just out of curiosity, do you think it is possible to make this
> > portable, assuming sh is available? On Windows it gives
> >
> >> system2("sh", env = c("VAR='Hello World'"), args = c("-c 'echo $VAR'"))
> > /rtools34/bin/sh: VAR=Hello World: No such file or directory
> > Warning message:
> > running command '"sh" VAR='Hello World' -c 'echo $VAR'' had status 127
> >
> > G.
>
> --
> Peter Dalgaard, Professor,
> Center for Statistics, Copenhagen Business School
> Solbjerg Plads 3, 2000 Frederiksberg, Denmark
> Phone: (+45)38153501
> Office: A 4.23
> Email: pd.mes using cbs.dk  Priv: PDalgd using gmail.com
>
>
>
>
>
>
>
>
>



More information about the R-devel mailing list