Title: Call R from R
Version: 3.7.6
Description: It is sometimes useful to perform a computation in a separate R process, without affecting the current R process at all. This packages does exactly that.
License: MIT + file LICENSE
URL: https://callr.r-lib.org, https://github.com/r-lib/callr
BugReports: https://github.com/r-lib/callr/issues
Depends: R (≥ 3.4)
Imports: processx (≥ 3.6.1), R6, utils
Suggests: asciicast (≥ 2.3.1), cli (≥ 1.1.0), mockery, ps, rprojroot, spelling, testthat (≥ 3.2.0), withr (≥ 2.3.0)
Config/Needs/website: r-lib/asciicast, glue, htmlwidgets, igraph, tibble, tidyverse/tidytemplate
Config/testthat/edition: 3
Encoding: UTF-8
Language: en-US
RoxygenNote: 7.3.1.9000
NeedsCompilation: no
Packaged: 2024-03-25 12:10:25 UTC; gaborcsardi
Author: Gábor Csárdi ORCID iD [aut, cre, cph], Winston Chang [aut], Posit Software, PBC [cph, fnd], Ascent Digital Services [cph, fnd]
Maintainer: Gábor Csárdi <csardi.gabor@gmail.com>
Repository: CRAN
Date/Publication: 2024-03-25 13:30:06 UTC

Call R from R

Description

It is sometimes useful to perform a computation in a separate R process, without affecting the current R process at all. This packages does exactly that.

callr

Features

Installation

Install the stable version from CRAN:

install.packages("callr")

Install the development version from GitHub:

pak::pak("r-lib/callr")

Synchronous, one-off R processes

Use r() to run an R function in a new R process. The results are passed back seamlessly:

callr::r(function() var(iris[, 1:4]))
#>              Sepal.Length Sepal.Width Petal.Length Petal.Width                  
#> Sepal.Length    0.6856935  -0.0424340    1.2743154   0.5162707                  
#> Sepal.Width    -0.0424340   0.1899794   -0.3296564  -0.1216394                  
#> Petal.Length    1.2743154  -0.3296564    3.1162779   1.2956094                  
#> Petal.Width     0.5162707  -0.1216394    1.2956094   0.5810063                  
Passing arguments

You can pass arguments to the function by setting args to the list of arguments. This is often necessary as these arguments are explicitly copied to the child process, whereas the evaluated function cannot refer to variables in the parent. For example, the following does not work:

mycars <- cars
callr::r(function() summary(mycars))
#> Error:                                                                          
#> ! in callr subprocess.                                                          
#> Caused by error in `summary(mycars)`:                                           
#> ! object 'mycars' not found                                                     
#> Type .Last.error to see the more details.                                       

But this does:

mycars <- cars
callr::r(function(x) summary(x), args = list(mycars))
#>      speed           dist                                                       
#>  Min.   : 4.0   Min.   :  2.00                                                  
#>  1st Qu.:12.0   1st Qu.: 26.00                                                  
#>  Median :15.0   Median : 36.00                                                  
#>  Mean   :15.4   Mean   : 42.98                                                  
#>  3rd Qu.:19.0   3rd Qu.: 56.00                                                  
#>  Max.   :25.0   Max.   :120.00                                                  

Note that the arguments will be serialized and saved to a file, so if they are large R objects, it might take a long time for the child process to start up.

Using packages

You can use any R package in the child process, just make sure to refer to it explicitly with the :: operator. For example, the following code creates an igraph graph in the child, and calculates some metrics of it.

callr::r(function() { g <- igraph::sample_gnp(1000, 4/1000); igraph::diameter(g) })
#> [1] 11                                                                          
Error handling

callr copies errors from the child process back to the main R session:

callr::r(function() 1 + "A")
#> Error:                                                                          
#> ! in callr subprocess.                                                          
#> Caused by error in `1 + "A"`:                                                   
#> ! non-numeric argument to binary operator                                       
#> Type .Last.error to see the more details.                                       
callr sets the `.Last.error` variable, and after an error you can inspect this for more details about the error, including stack traces both from the main R process and the subprocess.
.Last.error
#> Error:                                                                          
#> ! in callr subprocess.                                                          
#> Caused by error in `1 + "A"`:                                                   
#> ! non-numeric argument to binary operator                                       
#> ---                                                                             
#> Backtrace:                                                                      
#> 1. callr::r(function() 1 + "A")                                                 
#> 2. callr:::get_result(output = out, options)                                    
#> 3. callr:::throw(callr_remote_error(remerr, output), parent = fix_msg(remerr[[3]
#> ]))                                                                             
#> ---                                                                             
#> Subprocess backtrace:                                                           
#> 1. base::.handleSimpleError(function (e) …                                      
#> 2. global h(simpleError(msg, call))                                             

The error objects has two parts. The first belongs to the main process, and the second belongs to the subprocess.

.Last.error also includes a stack trace, that includes both the main R process and the subprocess:

The top part of the trace contains the frames in the main process, and the bottom part contains the frames in the subprocess, starting with the anonymous function.

Standard output and error

By default, the standard output and error of the child is lost, but you can request callr to redirect them to files, and then inspect the files in the parent:

x <- callr::r(function() { print("hello world!"); message("hello again!") },
  stdout = "/tmp/out", stderr = "/tmp/err"
)
readLines("/tmp/out")
#> [1] "[1] \"hello world!\""                                                      
readLines("/tmp/err")
#> [1] "hello again!"                                                              

With the stdout option, the standard output is collected and can be examined once the child process finished. The show = TRUE options will also show the output of the child, as it is printed, on the console of the parent.

Background R processes

r_bg() is similar to r() but it starts the R process in the background. It returns an r_process R6 object, that provides a rich API:

rp <- callr::r_bg(function() Sys.sleep(.2))
rp
#> PROCESS 'R', running, pid 58242.                                                

This is a list of all r_process methods:

ls(rp)
#>  [1] "as_ps_handle"          "clone"                 "finalize"                 
#>  [4] "format"                "get_cmdline"           "get_cpu_times"            
#>  [7] "get_error_connection"  "get_error_file"        "get_exe"                  
#> [10] "get_exit_status"       "get_input_connection"  "get_input_file"           
#> [13] "get_memory_info"       "get_name"              "get_output_connection"    
#> [16] "get_output_file"       "get_pid"               "get_poll_connection"      
#> [19] "get_result"            "get_start_time"        "get_status"               
#> [22] "get_username"          "get_wd"                "has_error_connection"     
#> [25] "has_input_connection"  "has_output_connection" "has_poll_connection"      
#> [28] "initialize"            "interrupt"             "is_alive"                 
#> [31] "is_incomplete_error"   "is_incomplete_output"  "is_supervised"            
#> [34] "kill"                  "kill_tree"             "poll_io"                  
#> [37] "print"                 "read_all_error"        "read_all_error_lines"     
#> [40] "read_all_output"       "read_all_output_lines" "read_error"               
#> [43] "read_error_lines"      "read_output"           "read_output_lines"        
#> [46] "resume"                "signal"                "supervise"                
#> [49] "suspend"               "wait"                  "write_input"              

These include all methods of the processx::process superclass and the new get_result() method, to retrieve the R object returned by the function call. Some of the handiest methods are:

Multiple background R processes and poll()

Multiple background R processes are best managed with the processx::poll() function that waits for events (standard output/error or termination) from multiple processes. It returns as soon as one process has generated an event, or if its timeout has expired. The timeout is in milliseconds.

rp1 <- callr::r_bg(function() { Sys.sleep(1/2); "1 done" })
rp2 <- callr::r_bg(function() { Sys.sleep(1/1000); "2 done" })
processx::poll(list(rp1, rp2), 1000)
#> [[1]]                                                                           
#>   output    error  process                                                      
#> "silent" "silent" "silent"                                                      
#>                                                                                 
#> [[2]]                                                                           
#>  output   error process                                                         
#> "ready" "ready" "ready"                                                         
#>                                                                                 
rp2$get_result()
#> [1] "2 done"                                                                    
processx::poll(list(rp1), 1000)
#> [[1]]                                                                           
#>   output    error  process                                                      
#> "silent" "silent"  "ready"                                                      
#>                                                                                 
rp1$get_result()
#> [1] "1 done"                                                                    

Persistent R sessions

r_session is another processx::process subclass that represents a persistent background R session:

rs <- callr::r_session$new()
rs
#> R SESSION, alive, idle, pid 58288.                                              

r_session$run() is a synchronous call, that works similarly to r(), but uses the persistent session. r_session$call() starts the function call and returns immediately. The r_session$poll_process() method or processx::poll() can then be used to wait for the completion or other events from one or more R sessions, R processes or other processx::process objects.

Once an R session is done with an asynchronous computation, its poll_process() method returns "ready" and the r_session$read() method can read out the result.

rs <- callr::r_session$new()
rs$run(function() runif(10))
#>  [1] 0.8047354 0.8938617 0.7142338 0.8505395 0.3118376 0.7083882 0.9514367      
#>  [8] 0.2536755 0.6727270 0.3359578                                              
rs$call(function() rnorm(10))
rs
#> R SESSION, alive, busy, pid 58294.                                              
rs$poll_process(2000)
#> [1] "ready"                                                                     
rs$read()
#> $code                                                                           
#> [1] 200                                                                         
#>                                                                                 
#> $message                                                                        
#> [1] "done callr-rs-result-e3324ebebc8b"                                         
#>                                                                                 
#> $result                                                                         
#>  [1] -0.60962697 -0.41063130  0.22121432  1.44621900  0.26890394  0.11432756    
#>  [7] -0.53206118  0.47493933  0.02069551  1.37348004                            
#>                                                                                 
#> $stdout                                                                         
#> [1] ""                                                                          
#>                                                                                 
#> $stderr                                                                         
#> [1] ""                                                                          
#>                                                                                 
#> $error                                                                          
#> NULL                                                                            
#>                                                                                 
#> attr(,"class")                                                                  
#> [1] "callr_session_result"                                                      

Running ⁠R CMD⁠ commands

The rcmd() function calls an ⁠R CMD⁠ command. For example, you can call ⁠R CMD INSTALL⁠, ⁠R CMD check⁠ or ⁠R CMD config⁠ this way:

callr::rcmd("config", "CC")
#> $status                                                                         
#> [1] 0                                                                           
#>                                                                                 
#> $stdout                                                                         
#> [1] "clang -arch arm64\n"                                                       
#>                                                                                 
#> $stderr                                                                         
#> [1] ""                                                                          
#>                                                                                 
#> $timeout                                                                        
#> [1] FALSE                                                                       
#>                                                                                 
#> $command                                                                        
#> [1] "/Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/bin/R"        
#> [2] "CMD"                                                                       
#> [3] "config"                                                                    
#> [4] "CC"                                                                        
#>                                                                                 

This returns a list with three components: the standard output, the standard error, and the exit (status) code of the ⁠R CMD⁠ command.

Configuration

Environment variables

Code of Conduct

Please note that the callr project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.

Author(s)

Maintainer: Gábor Csárdi csardi.gabor@gmail.com (ORCID) [copyright holder]

Authors:

Other contributors:

See Also

Useful links:


Add a user hook to be executed before launching an R subprocess

Description

This function allows users of callr to specify functions that get invoked whenever an R session is launched. The function can modify the environment variables and command line arguments.

Usage

add_hook(...)

Arguments

...

Named argument specifying a hook function to add, or NULL to delete the named hook.

Details

The prototype of the hook function is ⁠function (options)⁠, and it is expected to return the modified options.

Value

add_hook is called for its side-effects.


Convert and check function arguments

Description

This function is used for all variants of r and rcmd. An argument name is only used to refer to one kind of object, to make this possible.

Usage

convert_and_check_my_args(options)

Arguments

options

List of options.

Details

The benefit of having a single options object is to avoid passing around a lot of arguments all the time.

The benefit of making this object internal (i.e. that the r, etc. functions have multiple arguments instead of a single options list), is that documentation and usage is more user friendly (e.g. command- completion works in the editor.


Default value for the repos option in callr subprocesses

Description

callr sets the repos option in subprocesses, to make sure that a CRAN mirror is set up. This is because the subprocess cannot bring up the menu of CRAN mirrors for the user to choose from.

Usage

default_repos()

Value

Named character vector, the default value of the repos option in callr subprocesses.

Examples

default_repos()

Read the result object from the output file, or the error

Description

Even if an error happens, the output file might still exist, because saveRDS() creates the file before evaluating its object argument. So we need to check for the error file to decide if an error happened.

Usage

get_result(output, options)

Arguments

output

List of the output object from run() and the name of the result file to read. For the error file, .error is appended to this.

options

The context, including all parameters.

Value

If no error happened, the result is returned. Otherwise we handle the error.


Create an error object

Description

There are two kinds of errors, both have class callr_error:

  1. the first one is thrown after a timeout: callr_timeout_error.

  2. the second one is thrown after an R error (in the other session): callr_status_error.

Usage

new_callr_crash_error(out, msg = NULL)

Arguments

out

The object returned by run().

msg

An extra message to add to the error message.


Evaluate an expression in another R session

Description

From callr version 2.0.0, r() is equivalent to r_safe(), and tries to set up a less error prone execution environment. In particular:

Usage

r(
  func,
  args = list(),
  libpath = .libPaths(),
  repos = default_repos(),
  stdout = NULL,
  stderr = NULL,
  poll_connection = TRUE,
  error = getOption("callr.error", "error"),
  cmdargs = c("--slave", "--no-save", "--no-restore"),
  show = FALSE,
  callback = NULL,
  block_callback = NULL,
  spinner = show && interactive(),
  system_profile = FALSE,
  user_profile = "project",
  env = rcmd_safe_env(),
  timeout = Inf,
  package = FALSE,
  arch = "same",
  ...
)

r_safe(
  func,
  args = list(),
  libpath = .libPaths(),
  repos = default_repos(),
  stdout = NULL,
  stderr = NULL,
  poll_connection = TRUE,
  error = getOption("callr.error", "error"),
  cmdargs = c("--slave", "--no-save", "--no-restore"),
  show = FALSE,
  callback = NULL,
  block_callback = NULL,
  spinner = show && interactive(),
  system_profile = FALSE,
  user_profile = "project",
  env = rcmd_safe_env(),
  timeout = Inf,
  package = FALSE,
  arch = "same",
  ...
)

Arguments

func

Function object to call in the new R process. The function should be self-contained and only refer to other functions and use variables explicitly from other packages using the :: notation. By default the environment of the function is set to .GlobalEnv before passing it to the child process. (See the package option if you want to keep the environment.) Because of this, it is good practice to create an anonymous function and pass that to callr, instead of passing a function object from a (base or other) package. In particular

r(.libPaths)

does not work, because .libPaths is defined in a special environment, but

r(function() .libPaths())

works just fine.

args

Arguments to pass to the function. Must be a list.

libpath

The library path.

repos

The repos option. If NULL, then no repos option is set. This options is only used if user_profile or system_profile is set FALSE, as it is set using the system or the user profile.

stdout

The name of the file the standard output of the child R process will be written to. If the child process runs with the --slave option (the default), then the commands are not echoed and will not be shown in the standard output. Also note that you need to call print() explicitly to show the output of the command(s). IF NULL (the default), then standard output is not returned, but it is recorded and included in the error object if an error happens.

stderr

The name of the file the standard error of the child R process will be written to. In particular message() sends output to the standard error. If nothing was sent to the standard error, then this file will be empty. This argument can be the same file as stdout, in which case they will be correctly interleaved. If this is the string "2>&1", then standard error is redirected to standard output. IF NULL (the default), then standard output is not returned, but it is recorded and included in the error object if an error happens.

poll_connection

Whether to have a control connection to the process. This is used to transmit messages from the subprocess to the main process.

error

What to do if the remote process throws an error. See details below.

cmdargs

Command line arguments to pass to the R process. Note that c("-f", rscript) is appended to this, rscript is the name of the script file to run. This contains a call to the supplied function and some error handling code.

show

Logical, whether to show the standard output on the screen while the child process is running. Note that this is independent of the stdout and stderr arguments. The standard error is not shown currently.

callback

A function to call for each line of the standard output and standard error from the child process. It works together with the show option; i.e. if show = TRUE, and a callback is provided, then the output is shown of the screen, and the callback is also called.

block_callback

A function to call for each block of the standard output and standard error. This callback is not line oriented, i.e. multiple lines or half a line can be passed to the callback.

spinner

Whether to show a calming spinner on the screen while the child R session is running. By default it is shown if show = TRUE and the R session is interactive.

system_profile

Whether to use the system profile file.

user_profile

Whether to use the user's profile file. If this is "project", then only the profile from the working directory is used, but the R_PROFILE_USER environment variable and the user level profile are not. See also "Security considerations" below.

env

Environment variables to set for the child process.

timeout

Timeout for the function call to finish. It can be a base::difftime object, or a real number, meaning seconds. If the process does not finish before the timeout period expires, then a system_command_timeout_error error is thrown. Inf means no timeout.

package

Whether to keep the environment of func when passing it to the other package. Possible values are:

  • FALSE: reset the environment to .GlobalEnv. This is the default.

  • TRUE: keep the environment as is.

  • pkg: set the environment to the pkg package namespace.

arch

Architecture to use in the child process, for multi-arch builds of R. By default the same as the main process. See supported_archs(). If it contains a forward or backward slash character, then it is taken as the path to the R executable. Note that on Windows you need the path to Rterm.exe.

...

Extra arguments are passed to processx::run().

Details

The r() function from before 2.0.0 is called r_copycat() now.

Value

Value of the evaluated expression.

Error handling

callr handles errors properly. If the child process throws an error, then callr throws an error with the same error message in the main process.

The error expert argument may be used to specify a different behavior on error. The following values are possible:

The default error behavior can be also set using the callr.error option. This is useful to debug code that uses callr.

callr uses parent errors, to keep the stacks of the main process and the subprocess(es) in the same error object.

Security considerations

callr makes a copy of the user's .Renviron file and potentially of the local or user .Rprofile, in the session temporary directory. Avoid storing sensitive information such as passwords, in your environment file or your profile, otherwise this information will get scattered in various files, at least temporarily, until the subprocess finishes. You can use the keyring package to avoid passwords in plain files.

Transporting objects

func and args are copied to the child process by first serializing them into a temporary file using saveRDS() and then loading them back into the child session using readRDS(). The same strategy is used to copy the result of calling func(args) to the main session. Note that some objects, notably those with externalptr type, won't work as expected after being saved to a file and loaded back.

For performance reasons compress=FALSE is used when serializing with saveRDS(), this can be disabled by setting options(callr.compress_transport = TRUE).

See Also

Other callr functions: r_copycat(), r_vanilla()

Examples


# Workspace is empty
r(function() ls())

# library path is the same by default
r(function() .libPaths())
.libPaths()


Evaluate an expression in another R session, in the background

Description

Starts evaluating an R function call in a background R process, and returns immediately. Use p$get_result() to collect the result or to throw an error if the background computation failed.

Usage

r_bg(
  func,
  args = list(),
  libpath = .libPaths(),
  repos = default_repos(),
  stdout = "|",
  stderr = "|",
  poll_connection = TRUE,
  error = getOption("callr.error", "error"),
  cmdargs = c("--slave", "--no-save", "--no-restore"),
  system_profile = FALSE,
  user_profile = "project",
  env = rcmd_safe_env(),
  supervise = FALSE,
  package = FALSE,
  arch = "same",
  ...
)

Arguments

func

Function object to call in the new R process. The function should be self-contained and only refer to other functions and use variables explicitly from other packages using the :: notation. By default the environment of the function is set to .GlobalEnv before passing it to the child process. (See the package option if you want to keep the environment.) Because of this, it is good practice to create an anonymous function and pass that to callr, instead of passing a function object from a (base or other) package. In particular

r(.libPaths)

does not work, because .libPaths is defined in a special environment, but

r(function() .libPaths())

works just fine.

args

Arguments to pass to the function. Must be a list.

libpath

The library path.

repos

The repos option. If NULL, then no repos option is set. This options is only used if user_profile or system_profile is set FALSE, as it is set using the system or the user profile.

stdout

The name of the file the standard output of the child R process will be written to. If the child process runs with the --slave option (the default), then the commands are not echoed and will not be shown in the standard output. Also note that you need to call print() explicitly to show the output of the command(s). IF NULL (the default), then standard output is not returned, but it is recorded and included in the error object if an error happens.

stderr

The name of the file the standard error of the child R process will be written to. In particular message() sends output to the standard error. If nothing was sent to the standard error, then this file will be empty. This argument can be the same file as stdout, in which case they will be correctly interleaved. If this is the string "2>&1", then standard error is redirected to standard output. IF NULL (the default), then standard output is not returned, but it is recorded and included in the error object if an error happens.

poll_connection

Whether to have a control connection to the process. This is used to transmit messages from the subprocess to the main process.

error

What to do if the remote process throws an error. See details below.

cmdargs

Command line arguments to pass to the R process. Note that c("-f", rscript) is appended to this, rscript is the name of the script file to run. This contains a call to the supplied function and some error handling code.

system_profile

Whether to use the system profile file.

user_profile

Whether to use the user's profile file. If this is "project", then only the profile from the working directory is used, but the R_PROFILE_USER environment variable and the user level profile are not. See also "Security considerations" below.

env

Environment variables to set for the child process.

supervise

Whether to register the process with a supervisor. If TRUE, the supervisor will ensure that the process is killed when the R process exits.

package

Whether to keep the environment of func when passing it to the other package. Possible values are:

  • FALSE: reset the environment to .GlobalEnv. This is the default.

  • TRUE: keep the environment as is.

  • pkg: set the environment to the pkg package namespace.

arch

Architecture to use in the child process, for multi-arch builds of R. By default the same as the main process. See supported_archs(). If it contains a forward or backward slash character, then it is taken as the path to the R executable. Note that on Windows you need the path to Rterm.exe.

...

Extra arguments are passed to the processx::process constructor.

Value

An r_process object, which inherits from process, so all process methods can be called on it, and in addition it also has a get_result() method to collect the result.

Security considerations

callr makes a copy of the user's .Renviron file and potentially of the local or user .Rprofile, in the session temporary directory. Avoid storing sensitive information such as passwords, in your environment file or your profile, otherwise this information will get scattered in various files, at least temporarily, until the subprocess finishes. You can use the keyring package to avoid passwords in plain files.

Examples


rx <- r_bg(function() 1 + 2)

# wait until it is done
rx$wait()
rx$is_alive()
rx$get_result()


Run an R process that mimics the current R process

Description

Differences to r():

Usage

r_copycat(
  func,
  args = list(),
  libpath = .libPaths(),
  repos = getOption("repos"),
  cmdargs = "--slave",
  system_profile = TRUE,
  user_profile = TRUE,
  env = character(),
  ...
)

Arguments

func

Function object to call in the new R process. The function should be self-contained and only refer to other functions and use variables explicitly from other packages using the :: notation. By default the environment of the function is set to .GlobalEnv before passing it to the child process. (See the package option if you want to keep the environment.) Because of this, it is good practice to create an anonymous function and pass that to callr, instead of passing a function object from a (base or other) package. In particular

r(.libPaths)

does not work, because .libPaths is defined in a special environment, but

r(function() .libPaths())

works just fine.

args

Arguments to pass to the function. Must be a list.

libpath

The library path.

repos

The repos option. If NULL, then no repos option is set. This options is only used if user_profile or system_profile is set FALSE, as it is set using the system or the user profile.

cmdargs

Command line arguments to pass to the R process. Note that c("-f", rscript) is appended to this, rscript is the name of the script file to run. This contains a call to the supplied function and some error handling code.

system_profile

Whether to use the system profile file.

user_profile

Whether to use the user's profile file. If this is "project", then only the profile from the working directory is used, but the R_PROFILE_USER environment variable and the user level profile are not. See also "Security considerations" below.

env

Environment variables to set for the child process.

...

Additional arguments are passed to r().

Security considerations

callr makes a copy of the user's .Renviron file and potentially of the local or user .Rprofile, in the session temporary directory. Avoid storing sensitive information such as passwords, in your environment file or your profile, otherwise this information will get scattered in various files, at least temporarily, until the subprocess finishes. You can use the keyring package to avoid passwords in plain files.

See Also

Other callr functions: r_vanilla(), r()


External R Process

Description

An R process that runs in the background. This is an R6 class that extends the processx::process class. The process starts in the background, evaluates an R function call, and then quits.

Super class

processx::process -> r_process

Methods

Public methods

Inherited methods

Method new()

Start a new R process in the background.

Usage
r_process$new(options)
Arguments
options

A list of options created via r_process_options().

Returns

A new r_process object.


Method get_result()

Return the result, an R object, from a finished background R process. If the process has not finished yet, it throws an error. (You can use wait() method (see processx::process) to wait for the process to finish, optionally with a timeout.) You can also use processx::poll() to wait for the end of the process, together with other processes or events.

Usage
r_process$get_result()
Returns

The return value of the R expression evaluated in the R process.


Method finalize()

Clean up temporary files once an R process has finished and its handle is garbage collected.

Usage
r_process$finalize()

Method clone()

The objects of this class are cloneable with this method.

Usage
r_process$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples


## List all options and their default values:
r_process_options()

## Start an R process in the background, wait for it, get result
opts <- r_process_options(func = function() 1 + 1)
rp <- r_process$new(opts)
rp$wait()
rp$get_result()


Create options for an r_process object

Description

Create options for an r_process object

Usage

r_process_options(...)

Arguments

...

Options to override, named arguments.

Value

A list of options.

r_process_options() creates a set of options to initialize a new object from the r_process class. Its arguments must be named, the names are used as option names. The options correspond to (some of) the arguments of the r() function. At least the func option must be specified, this is the R function to run in the background.

Examples

## List all options and their default values:
r_process_options()

External R Session

Description

A permanent R session that runs in the background. This is an R6 class that extends the processx::process class.

The process is started at the creation of the object, and then it can be used to evaluate R function calls, one at a time.

Super class

processx::process -> r_session

Public fields

status

Status codes returned by read().

Methods

Public methods

Inherited methods

Method new()

creates a new R background process. It can wait for the process to start up (wait = TRUE), or return immediately, i.e. before the process is actually ready to run. In the latter case you may call the poll_process() method to make sure it is ready.

Usage
r_session$new(options = r_session_options(), wait = TRUE, wait_timeout = 3000)
Arguments
options

A list of options created via r_session_options().

wait

Whether to wait for the R process to start and be ready for running commands.

wait_timeout

Timeout for waiting for the R process to start, in milliseconds.

Returns

An r_session object.


Method run()

Similar to r(), but runs the function in a permanent background R session. It throws an error if the function call generated an error in the child process.

Usage
r_session$run(func, args = list(), package = FALSE)
Arguments
func

Function object to call in the background R process. Please read the notes for the similar argument of r().

args

Arguments to pass to the function. Must be a list.

package

Whether to keep the environment of func when passing it to the other package. Possible values are:

  • FALSE: reset the environment to .GlobalEnv. This is the default.

  • TRUE: keep the environment as is.

  • pkg: set the environment to the pkg package namespace.

Returns

The return value of the R expression.


Method run_with_output()

Similar to ⁠$run()⁠, but returns the standard output and error of the child process as well. It does not throw on errors, but returns a non-NULL error member in the result list.

Usage
r_session$run_with_output(func, args = list(), package = FALSE)
Arguments
func

Function object to call in the background R process. Please read the notes for the similar argument of r().

args

Arguments to pass to the function. Must be a list.

package

Whether to keep the environment of func when passing it to the other package. Possible values are:

  • FALSE: reset the environment to .GlobalEnv. This is the default.

  • TRUE: keep the environment as is.

  • pkg: set the environment to the pkg package namespace.

Returns

A list with the following entries.


Method call()

Starts running a function in the background R session, and returns immediately. To check if the function is done, call the poll_process() method.

Usage
r_session$call(func, args = list(), package = FALSE)
Arguments
func

Function object to call in the background R process. Please read the notes for the similar argument of r().

args

Arguments to pass to the function. Must be a list.

package

Whether to keep the environment of func when passing it to the other package. Possible values are:

  • FALSE: reset the environment to .GlobalEnv. This is the default.

  • TRUE: keep the environment as is.

  • pkg: set the environment to the pkg package namespace.


Method poll_process()

Poll the R session with a timeout. If the session has finished the computation, it returns with "ready". If the timeout is reached, it returns with "timeout".

Usage
r_session$poll_process(timeout)
Arguments
timeout

Timeout period in milliseconds.

Returns

Character string "ready" or "timeout".


Method get_state()

Return the state of the R session.

Usage
r_session$get_state()
Returns

Possible values:


Method get_running_time()

Returns the elapsed time since the R process has started, and the elapsed time since the current computation has started. The latter is NA if there is no active computation.

Usage
r_session$get_running_time()
Returns

Named vector of POSIXct objects. The names are "total" and "current".


Method read()

Reads an event from the child process, if there is one available. Events might signal that the function call has finished, or they can be progress report events.

This is a low level function that you only need to use if you want to process events (messages) from the R session manually.

Usage
r_session$read()
Returns

NULL if no events are available. Otherwise a named list, which is also a callr_session_result object. The list always has a code entry which is the type of the event. See also r_session$public_fields$status for symbolic names of the event types.


Method close()

Terminate the current computation and the R process. The session object will be in "finished" state after this.

Usage
r_session$close(grace = 1000)
Arguments
grace

Grace period in milliseconds, to wait for the subprocess to exit cleanly, after its standard input is closed. If the process is still running after this period, it will be killed.


Method traceback()

The traceback() method can be used after an error in the R subprocess. It is equivalent to the base::traceback() call, in the subprocess.

On callr version 3.8.0 and above, you need to set the callr.traceback option to TRUE (in the main process) to make the subprocess save the trace on error. This is because saving the trace can be costly for large objects passed as arguments.

Usage
r_session$traceback()
Returns

The same output as from base::traceback()


Method debug()

Interactive debugger to inspect the dumped frames in the subprocess, after an error. See more at r_session_debug.

On callr version 3.8.0 and above, you need to set the callr.traceback option to TRUE (in the main process) to make the subprocess dump frames on error. This is because saving the frames can be costly for large objects passed as arguments.

Usage
r_session$debug()

Method attach()

Experimental function that provides a REPL (Read-Eval-Print-Loop) to the subprocess.

Usage
r_session$attach()

Method finalize()

Finalizer that is called when garbage collecting an r_session object, to clean up temporary files.

Usage
r_session$finalize()

Method print()

Print method for an r_session.

Usage
r_session$print(...)
Arguments
...

Arguments are not used currently.


Method clone()

The objects of this class are cloneable with this method.

Usage
r_session$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples


rs <- r_ression$new()

rs$run(function() 1 + 2)

rs$call(function() Sys.sleep(1))
rs$get_state()

rs$poll_process(-1)
rs$get_state()
rs$read()


Interactive debugging of persistent R sessions

Description

The r_session$debug() method is an interactive debugger to inspect the stack of the background process after an error.

Details

Note that on callr version 3.8.0 and above, you need to set the callr.traceback option to TRUE (in the main process) to make the subprocess dump the frames on error. This is because saving the frames can be costly for large objects passed as arguments.

⁠$debug()⁠ starts a REPL (Read-Eval-Print-Loop), that evaluates R expressions in the subprocess. It is similar to browser() and debugger() and also has some extra commands:

To exit the debugger, press the usual interrupt key, i.e. CTRL+c or ESC in some GUIs.

Here is an example session that uses ⁠$debug()⁠ (some output is omitted for brevity):

# ----------------------------------------------------------------------
> rs <- r_session$new()
> rs$run(function() knitr::knit("no-such-file"))
Error in rs_run(self, private, func, args) :
 callr subprocess failed: cannot open the connection

> rs$debug()
Debugging in process 87361, press CTRL+C (ESC) to quit. Commands:
  .where       -- print stack trace
  .inspect <n> -- inspect a frame, 0 resets to .GlobalEnv
  .help        -- print this message
  <cmd>        -- run <cmd> in frame or .GlobalEnv

3: file(con, "r")
2: readLines(input2, encoding = "UTF-8", warn = FALSE)
1: knitr::knit("no-such-file") at #1

RS 87361 > .inspect 1

RS 87361 (frame 1) > ls()
 [1] "encoding"  "envir"     "ext"       "in.file"   "input"     "input.dir"
 [7] "input2"    "ocode"     "oconc"     "oenvir"    "oopts"     "optc"
[13] "optk"      "otangle"   "out.purl"  "output"    "quiet"     "tangle"
[19] "text"

RS 87361 (frame 1) > input
[1] "no-such-file"

RS 87361 (frame 1) > file.exists(input)
[1] FALSE

RS 87361 (frame 1) > # <CTRL + C>
# ----------------------------------------------------------------------

Create options for an r_session object

Description

Create options for an r_session object

Usage

r_session_options(...)

Arguments

...

Options to override, named arguments.

Value

Named list of options.

The current options are:

Call r_session_options() to see the default values. r_session_options() might contain undocumented entries, you cannot change these.

Examples

r_session_options()

Run an R child process, with no configuration

Description

It tries to mimic a fresh R installation. In particular:

Usage

r_vanilla(
  func,
  args = list(),
  libpath = character(),
  repos = c(CRAN = "@CRAN@"),
  cmdargs = "--slave",
  system_profile = FALSE,
  user_profile = FALSE,
  env = character(),
  ...
)

Arguments

func

Function object to call in the new R process. The function should be self-contained and only refer to other functions and use variables explicitly from other packages using the :: notation. By default the environment of the function is set to .GlobalEnv before passing it to the child process. (See the package option if you want to keep the environment.) Because of this, it is good practice to create an anonymous function and pass that to callr, instead of passing a function object from a (base or other) package. In particular

r(.libPaths)

does not work, because .libPaths is defined in a special environment, but

r(function() .libPaths())

works just fine.

args

Arguments to pass to the function. Must be a list.

libpath

The library path.

repos

The repos option. If NULL, then no repos option is set. This options is only used if user_profile or system_profile is set FALSE, as it is set using the system or the user profile.

cmdargs

Command line arguments to pass to the R process. Note that c("-f", rscript) is appended to this, rscript is the name of the script file to run. This contains a call to the supplied function and some error handling code.

system_profile

Whether to use the system profile file.

user_profile

Whether to use the user's profile file. If this is "project", then only the profile from the working directory is used, but the R_PROFILE_USER environment variable and the user level profile are not. See also "Security considerations" below.

env

Environment variables to set for the child process.

...

Additional arguments are passed to r().

Security considerations

callr makes a copy of the user's .Renviron file and potentially of the local or user .Rprofile, in the session temporary directory. Avoid storing sensitive information such as passwords, in your environment file or your profile, otherwise this information will get scattered in various files, at least temporarily, until the subprocess finishes. You can use the keyring package to avoid passwords in plain files.

See Also

Other callr functions: r_copycat(), r()

Examples


# Compare to r()
r(function() .libPaths())
r_vanilla(function() .libPaths())

r(function() getOption("repos"))
r_vanilla(function() getOption("repos"))


Run an ⁠R CMD⁠ command

Description

Run an ⁠R CMD⁠ command form within R. This will usually start another R process, from a shell script.

Usage

rcmd(
  cmd,
  cmdargs = character(),
  libpath = .libPaths(),
  repos = default_repos(),
  stdout = NULL,
  stderr = NULL,
  poll_connection = TRUE,
  echo = FALSE,
  show = FALSE,
  callback = NULL,
  block_callback = NULL,
  spinner = show && interactive(),
  system_profile = FALSE,
  user_profile = "project",
  env = rcmd_safe_env(),
  timeout = Inf,
  wd = ".",
  fail_on_status = FALSE,
  ...
)

rcmd_safe(
  cmd,
  cmdargs = character(),
  libpath = .libPaths(),
  repos = default_repos(),
  stdout = NULL,
  stderr = NULL,
  poll_connection = TRUE,
  echo = FALSE,
  show = FALSE,
  callback = NULL,
  block_callback = NULL,
  spinner = show && interactive(),
  system_profile = FALSE,
  user_profile = "project",
  env = rcmd_safe_env(),
  timeout = Inf,
  wd = ".",
  fail_on_status = FALSE,
  ...
)

Arguments

cmd

Command to run. See R --help from the command line for the various commands. In the current version of R (3.2.4) these are: BATCH, COMPILE, SHLIB, INSTALL, REMOVE, build, check, LINK, Rprof, Rdconv, Rd2pdf, Rd2txt, Stangle, Sweave, Rdiff, config, javareconf, rtags.

cmdargs

Command line arguments.

libpath

The library path.

repos

The repos option. If NULL, then no repos option is set. This options is only used if user_profile or system_profile is set FALSE, as it is set using the system or the user profile.

stdout

Optionally a file name to send the standard output to.

stderr

Optionally a file name to send the standard error to. It may be the same as stdout, in which case standard error is redirected to standard output. It can also be the special string "2>&1", in which case standard error will be redirected to standard output.

poll_connection

Whether to have a control connection to the process. This is used to transmit messages from the subprocess to the parent.

echo

Whether to echo the complete command run by rcmd.

show

Logical, whether to show the standard output on the screen while the child process is running. Note that this is independent of the stdout and stderr arguments. The standard error is not shown currently.

callback

A function to call for each line of the standard output and standard error from the child process. It works together with the show option; i.e. if show = TRUE, and a callback is provided, then the output is shown of the screen, and the callback is also called.

block_callback

A function to call for each block of the standard output and standard error. This callback is not line oriented, i.e. multiple lines or half a line can be passed to the callback.

spinner

Whether to show a calming spinner on the screen while the child R session is running. By default it is shown if show = TRUE and the R session is interactive.

system_profile

Whether to use the system profile file.

user_profile

Whether to use the user's profile file. If this is "project", then only the profile from the working directory is used, but the R_PROFILE_USER environment variable and the user level profile are not. See also "Security considerations" below.

env

Environment variables to set for the child process.

timeout

Timeout for the function call to finish. It can be a base::difftime object, or a real number, meaning seconds. If the process does not finish before the timeout period expires, then a system_command_timeout_error error is thrown. Inf means no timeout.

wd

Working directory to use for running the command. Defaults to the current working directory.

fail_on_status

Whether to throw an R error if the command returns with a non-zero status code. By default no error is thrown.

...

Extra arguments are passed to processx::run().

Details

Starting from callr 2.0.0, rcmd() has safer defaults, the same as the rcmd_safe() default values. Use rcmd_copycat() for the old defaults.

Value

A list with the command line ⁠$command⁠), standard output (⁠$stdout⁠), standard error (stderr), exit status (⁠$status⁠) of the external ⁠R CMD⁠ command, and whether a timeout was reached (⁠$timeout⁠).

Security considerations

callr makes a copy of the user's .Renviron file and potentially of the local or user .Rprofile, in the session temporary directory. Avoid storing sensitive information such as passwords, in your environment file or your profile, otherwise this information will get scattered in various files, at least temporarily, until the subprocess finishes. You can use the keyring package to avoid passwords in plain files.

See Also

Other R CMD commands: rcmd_bg(), rcmd_copycat()

Examples


rcmd("config", "CC")


Run an ⁠R CMD⁠ command in the background

Description

The child process is started in the background, and the function return immediately.

Usage

rcmd_bg(
  cmd,
  cmdargs = character(),
  libpath = .libPaths(),
  stdout = "|",
  stderr = "|",
  poll_connection = TRUE,
  repos = default_repos(),
  system_profile = FALSE,
  user_profile = "project",
  env = rcmd_safe_env(),
  wd = ".",
  supervise = FALSE,
  ...
)

Arguments

cmd

Command to run. See R --help from the command line for the various commands. In the current version of R (3.2.4) these are: BATCH, COMPILE, SHLIB, INSTALL, REMOVE, build, check, LINK, Rprof, Rdconv, Rd2pdf, Rd2txt, Stangle, Sweave, Rdiff, config, javareconf, rtags.

cmdargs

Command line arguments.

libpath

The library path.

stdout

Optionally a file name to send the standard output to.

stderr

Optionally a file name to send the standard error to. It may be the same as stdout, in which case standard error is redirected to standard output. It can also be the special string "2>&1", in which case standard error will be redirected to standard output.

poll_connection

Whether to have a control connection to the process. This is used to transmit messages from the subprocess to the parent.

repos

The repos option. If NULL, then no repos option is set. This options is only used if user_profile or system_profile is set FALSE, as it is set using the system or the user profile.

system_profile

Whether to use the system profile file.

user_profile

Whether to use the user's profile file. If this is "project", then only the profile from the working directory is used, but the R_PROFILE_USER environment variable and the user level profile are not. See also "Security considerations" below.

env

Environment variables to set for the child process.

wd

Working directory to use for running the command. Defaults to the current working directory.

supervise

Whether to register the process with a supervisor. If TRUE, the supervisor will ensure that the process is killed when the R process exits.

...

Extra arguments are passed to the processx::process constructor.

Value

It returns a process object.

Security considerations

callr makes a copy of the user's .Renviron file and potentially of the local or user .Rprofile, in the session temporary directory. Avoid storing sensitive information such as passwords, in your environment file or your profile, otherwise this information will get scattered in various files, at least temporarily, until the subprocess finishes. You can use the keyring package to avoid passwords in plain files.

See Also

Other R CMD commands: rcmd_copycat(), rcmd()


Call and ⁠R CMD⁠ command, while mimicking the current R session

Description

This function is similar to rcmd(), but it has slightly different defaults:

Usage

rcmd_copycat(
  cmd,
  cmdargs = character(),
  libpath = .libPaths(),
  repos = getOption("repos"),
  env = character(),
  ...
)

Arguments

cmd

Command to run. See R --help from the command line for the various commands. In the current version of R (3.2.4) these are: BATCH, COMPILE, SHLIB, INSTALL, REMOVE, build, check, LINK, Rprof, Rdconv, Rd2pdf, Rd2txt, Stangle, Sweave, Rdiff, config, javareconf, rtags.

cmdargs

Command line arguments.

libpath

The library path.

repos

The repos option. If NULL, then no repos option is set. This options is only used if user_profile or system_profile is set FALSE, as it is set using the system or the user profile.

env

Environment variables to set for the child process.

...

Additional arguments are passed to rcmd().

Security considerations

callr makes a copy of the user's .Renviron file and potentially of the local or user .Rprofile, in the session temporary directory. Avoid storing sensitive information such as passwords, in your environment file or your profile, otherwise this information will get scattered in various files, at least temporarily, until the subprocess finishes. You can use the keyring package to avoid passwords in plain files.

See Also

Other R CMD commands: rcmd_bg(), rcmd()


External ⁠R CMD⁠ Process

Description

An ⁠R CMD *⁠ command that runs in the background. This is an R6 class that extends the processx::process class.

Super class

processx::process -> rcmd_process

Methods

Public methods

Inherited methods

Method new()

Start an ⁠R CMD⁠ process.

Usage
rcmd_process$new(options)
Arguments
options

A list of options created via rcmd_process_options().

Returns

A new rcmd_process object.


Method finalize()

Clean up the temporary files created for an ⁠R CMD⁠ process.

Usage
rcmd_process$finalize()

Method clone()

The objects of this class are cloneable with this method.

Usage
rcmd_process$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples


options <- rcmd_process_options(cmd = "config", cmdargs = "CC")
rp <- rcmd_process$new(options)
rp$wait()
rp$read_output_lines()


Create options for an rcmd_process object

Description

Create options for an rcmd_process object

Usage

rcmd_process_options(...)

Arguments

...

Options to override, named arguments.

Value

A list of options.

rcmd_process_options() creates a set of options to initialize a new object from the rcmd_process class. Its arguments must be named, the names are used as option names. The options correspond to (some of) the arguments of the rcmd() function. At least the cmd option must be specified, to select the ⁠R CMD⁠ subcommand to run. Typically cmdargs is specified as well, to supply more arguments to ⁠R CMD⁠.

Examples

## List all options and their default values:
rcmd_process_options()

rcmd_safe_env returns a set of environment variables that are more appropriate for rcmd_safe(). It is exported to allow manipulating these variables (e.g. add an extra one), before passing them to the rcmd() functions.

Description

It currently has the following variables:

Usage

rcmd_safe_env()

Details

Note that callr also sets the R_ENVIRON, R_ENVIRON_USER, R_PROFILE and R_PROFILE_USER environment variables appropriately, unless these are set by the user in the env argument of the r, etc. calls.

Value

A named character vector of environment variables.


Objects exported from other packages

Description

These objects are imported from other packages. Follow the links below to see their documentation.

processx

poll, process, run


Run an R script

Description

It uses the Rscript program corresponding to the current R version, to run the script. It streams stdout and stderr of the process.

Usage

rscript(
  script,
  cmdargs = character(),
  libpath = .libPaths(),
  repos = default_repos(),
  stdout = NULL,
  stderr = NULL,
  poll_connection = TRUE,
  echo = FALSE,
  show = TRUE,
  callback = NULL,
  block_callback = NULL,
  spinner = FALSE,
  system_profile = FALSE,
  user_profile = "project",
  env = rcmd_safe_env(),
  timeout = Inf,
  wd = ".",
  fail_on_status = TRUE,
  color = TRUE,
  ...
)

Arguments

script

Path of the script to run.

cmdargs

Command line arguments.

libpath

The library path.

repos

The repos option. If NULL, then no repos option is set. This options is only used if user_profile or system_profile is set FALSE, as it is set using the system or the user profile.

stdout

Optionally a file name to send the standard output to.

stderr

Optionally a file name to send the standard error to. It may be the same as stdout, in which case standard error is redirected to standard output. It can also be the special string "2>&1", in which case standard error will be redirected to standard output.

poll_connection

Whether to have a control connection to the process. This is used to transmit messages from the subprocess to the parent.

echo

Whether to echo the complete command run by rcmd.

show

Logical, whether to show the standard output on the screen while the child process is running. Note that this is independent of the stdout and stderr arguments. The standard error is not shown currently.

callback

A function to call for each line of the standard output and standard error from the child process. It works together with the show option; i.e. if show = TRUE, and a callback is provided, then the output is shown of the screen, and the callback is also called.

block_callback

A function to call for each block of the standard output and standard error. This callback is not line oriented, i.e. multiple lines or half a line can be passed to the callback.

spinner

Whether to show a calming spinner on the screen while the child R session is running. By default it is shown if show = TRUE and the R session is interactive.

system_profile

Whether to use the system profile file.

user_profile

Whether to use the user's profile file. If this is "project", then only the profile from the working directory is used, but the R_PROFILE_USER environment variable and the user level profile are not. See also "Security considerations" below.

env

Environment variables to set for the child process.

timeout

Timeout for the function call to finish. It can be a base::difftime object, or a real number, meaning seconds. If the process does not finish before the timeout period expires, then a system_command_timeout_error error is thrown. Inf means no timeout.

wd

Working directory to use for running the command. Defaults to the current working directory.

fail_on_status

Whether to throw an R error if the command returns with a non-zero status code. By default no error is thrown.

color

Whether to use terminal colors in the child process, assuming they are active in the parent process.

...

Extra arguments are passed to processx::run().

Security considerations

callr makes a copy of the user's .Renviron file and potentially of the local or user .Rprofile, in the session temporary directory. Avoid storing sensitive information such as passwords, in your environment file or your profile, otherwise this information will get scattered in various files, at least temporarily, until the subprocess finishes. You can use the keyring package to avoid passwords in plain files.


External Rscript process

Description

An ⁠Rscript script.R⁠ command that runs in the background. This is an R6 class that extends the processx::process class.

Super class

processx::process -> rscript_process

Methods

Public methods

Inherited methods

Method new()

Create a new Rscript process.

Usage
rscript_process$new(options)
Arguments
options

A list of options created via rscript_process_options().


Method finalize()

Clean up after an Rsctipt process, remove temporary files.

Usage
rscript_process$finalize()

Method clone()

The objects of this class are cloneable with this method.

Usage
rscript_process$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples


options <- rscript_process_options(script = "script.R")
rp <- rscript_process$new(options)
rp$wait()
rp$read_output_lines()


Create options for an rscript_process object

Description

Create options for an rscript_process object

Usage

rscript_process_options(...)

Arguments

...

Options to override, named arguments.

Value

A list of options.

rscript_process_options() creates a set of options to initialize a new object from the rscript_process class. Its arguments must be named, the names are used as option names. The options correspond to (some of) the arguments of the rscript() function. At least the script option must be specified, the script file to run.

Examples

## List all options and their default values:
rscript_process_options()

Find supported sub-architectures for the current R installation

Description

This function uses a heuristic, which might fail, so its result should be taken as a best guess.

Usage

supported_archs()

Value

Character vector of supported architectures. If the current R build is not a multi-architecture build, then an empty string scalar is returned.

Examples

supported_archs()