Package ‘callr’March 28, 2020
Title Call R from R
Version 3.4.3
Description It is sometimes useful to perform a computation in aseparate R process, without affecting the current R process at all.This packages does exactly that.
License MIT + file LICENSE
LazyData true
URL https://github.com/r-lib/callr#readme
BugReports https://github.com/r-lib/callr/issues
RoxygenNote 7.0.2
Imports processx (>= 3.4.0), R6, utils
Suggests cliapp, covr, crayon, fansi, pingr, ps, rprojroot, spelling,testthat, tibble, withr
Encoding UTF-8
Language en-US
NeedsCompilation no
Author Gábor Csárdi [aut, cre, cph] (<https://orcid.org/0000-0001-7098-9676>),Winston Chang [aut],RStudio [cph, fnd],Mango Solutions [cph, fnd]
Maintainer Gábor Csárdi <[email protected]>
Repository CRAN
Date/Publication 2020-03-28 05:50:17 UTC
R topics documented:callr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2default_repos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3r . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3rcmd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1
2 callr
rcmd_bg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9rcmd_copycat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11rcmd_process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12rcmd_process_options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13rcmd_safe_env . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14rscript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14rscript_process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16rscript_process_options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17r_bg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18r_copycat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20r_process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22r_process_options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23r_session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24r_session_debug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28r_session_options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29r_vanilla . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Index 32
callr Call R from R
Description
It is sometimes useful to perform a computation in a separate R process, without affecting thecurrent R process at all. This packages does exactly that.
Author(s)
Maintainer: Gábor Csárdi <[email protected]> (ORCID) [copyright holder]
Authors:
• Winston Chang
Other contributors:
• RStudio [copyright holder, funder]
• Mango Solutions [copyright holder, funder]
See Also
Useful links:
• https://github.com/r-lib/callr#readme
• Report bugs at https://github.com/r-lib/callr/issues
default_repos 3
default_repos 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 isbecause 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()
r 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 proneexecution environment. In particular:
• It makes sure that at least one reasonable CRAN mirror is set up.
• Adds some command line arguments are added to avoid saving .RData files, etc.
• Ignores the system and user profiles.
• Various environment variables are set: CYGWIN to avoid warnings about DOS-style paths,R_TESTS to avoid issues when callr is invoked from unit tests, R_BROWSER and R_PDFVIEWERto avoid starting a browser or a PDF viewer. See rcmd_safe_env().
Usage
r(func,args = list(),libpath = .libPaths(),repos = default_repos(),stdout = NULL,stderr = NULL,poll_connection = TRUE,
4 r
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,...
)
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,...
)
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 fromother packages using the :: notation. The environment of the function is set to.GlobalEnv before passing it to the child process. Because of this, it is goodpractice to create an anonymous function and pass that to callr, instead ofpassing 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.
r 5
libpath The library path.
repos The repos option. If NULL, then no repos option is set. This options is onlyused if user_profile or system_profile is set FALSE, as it is set using thesystem or the user profile.
stdout The name of the file the standard output of the child R process will be writtento. If the child process runs with the --slave option (the default), then the com-mands are not echoed and will not be shown in the standard output. Also notethat you need to call print() explicitly to show the output of the command(s).
stderr The name of the file the standard error of the child R process will be writtento. In particular message() sends output to the standard error. If nothing wassent to the standard error, then this file will be empty. This argument can be thesame file as stdout, in which case they will be correctly interleaved. If this isthe string "2>&1", then standard error is redirected to standard output.
poll_connection
Whether to have a control connection to the process. This is used to transmitmessages 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 containsa call to the supplied function and some error handling code.
show Logical, whether to show the standard output on the screen while the child pro-cess is running. Note that this is independent of the stdout and stderr argu-ments. The standard error is not shown currently.
callback A function to call for each line of the standard output and standard error from thechild process. It works together with the show option; i.e. if show = TRUE, and acallback is provided, then the output is shown of the screen, and the callback isalso called.
block_callback A function to call for each block of the standard output and standard error. Thiscallback is not line oriented, i.e. multiple lines or half a line can be passed to thecallback.
spinner Whether to show a calming spinner on the screen while the child R session isrunning. 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 pro-file from the working directory is used, but the R_PROFILE_USER environmentvariable 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 areal number, meaning seconds. If the process does not finish before the timeoutperiod expires, then a system_command_timeout_error error is thrown. Infmeans no timeout.
... Extra arguments are passed to processx::run().
6 r
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 withthe same error message in the main process.
The error expert argument may be used to specify a different behavior on error. The followingvalues are possible:
• error is the default behavior: throw an error in the main process, with a prefix and the sameerror message as in the subprocess.
• stack also throws an error in the main process, but the error is of a special kind, classcallr_error, and it contains both the original error object, and the call stack of the child,as written out by utils::dump.frames(). This is now deprecated, because the error thrownfor "error" has the same information.
• debugger is similar to stack, but in addition to returning the complete call stack, it also startup a debugger in the child call stack, via utils::debugger().
The default error behavior can be also set using the callr.error option. This is useful to debugcode that uses callr.
callr uses parent errors, to keep the stacks of the main process and the subprocess(es) in the sameerror 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 yourenvironment file or your profile, otherwise this information will get scattered in various files, at leasttemporarily, until the subprocess finishes. You can use the keyring package to avoid passwords inplain files.
See Also
Other callr functions: r_copycat(), r_vanilla()
Examples
# Workspace is emptyr(function() ls())
# library path is the same by defaultr(function() .libPaths()).libPaths()
rcmd 7
rcmd Run an R CMD command
Description
Run an R CMD command form within R. This will usually start another R process, from a shellscript.
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",
8 rcmd
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 com-mands. 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 onlyused if user_profile or system_profile is set FALSE, as it is set using thesystem 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 asstdout, in which case standard error is redirected to standard output. It can alsobe the special string "2>&1", in which case standard error will be redirected tostandard output.
poll_connection
Whether to have a control connection to the process. This is used to transmitmessages 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 pro-cess is running. Note that this is independent of the stdout and stderr argu-ments. The standard error is not shown currently.
callback A function to call for each line of the standard output and standard error from thechild process. It works together with the show option; i.e. if show = TRUE, and acallback is provided, then the output is shown of the screen, and the callback isalso called.
block_callback A function to call for each block of the standard output and standard error. Thiscallback is not line oriented, i.e. multiple lines or half a line can be passed to thecallback.
spinner Whether to show a calming spinner on the screen while the child R session isrunning. 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 pro-file from the working directory is used, but the R_PROFILE_USER environmentvariable and the user level profile are not. See also "Security considerations"below.
env Environment variables to set for the child process.
rcmd_bg 9
timeout Timeout for the function call to finish. It can be a base::difftime object, or areal number, meaning seconds. If the process does not finish before the timeoutperiod expires, then a system_command_timeout_error error is thrown. Infmeans no timeout.
wd Working directory to use for running the command. Defaults to the currentworking 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), exitstatus ($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 yourenvironment file or your profile, otherwise this information will get scattered in various files, at leasttemporarily, until the subprocess finishes. You can use the keyring package to avoid passwords inplain files.
See Also
Other R CMD commands: rcmd_bg(), rcmd_copycat()
Examples
rcmd("config", "CC")
rcmd_bg Run an R CMD command in the background
Description
The child process is started in the background, and the function return immediately.
10 rcmd_bg
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 com-mands. 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 asstdout, in which case standard error is redirected to standard output. It can alsobe the special string "2>&1", in which case standard error will be redirected tostandard output.
poll_connection
Whether to have a control connection to the process. This is used to transmitmessages from the subprocess to the parent.
repos The repos option. If NULL, then no repos option is set. This options is onlyused if user_profile or system_profile is set FALSE, as it is set using thesystem 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 pro-file from the working directory is used, but the R_PROFILE_USER environmentvariable 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 currentworking directory.
rcmd_copycat 11
supervise Whether to register the process with a supervisor. If TRUE, the supervisor willensure 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 yourenvironment file or your profile, otherwise this information will get scattered in various files, at leasttemporarily, until the subprocess finishes. You can use the keyring package to avoid passwords inplain files.
See Also
Other R CMD commands: rcmd_copycat(), rcmd()
rcmd_copycat Call and R CMD command, while mimicking the current R session
Description
This function is similar to rcmd(), but it has slightly different defaults:
• The repos options is unchanged.
• No extra environment variables are defined.
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 com-mands. 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.
12 rcmd_process
cmdargs Command line arguments.
libpath The library path.
repos The repos option. If NULL, then no repos option is set. This options is onlyused if user_profile or system_profile is set FALSE, as it is set using thesystem 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 yourenvironment file or your profile, otherwise this information will get scattered in various files, at leasttemporarily, until the subprocess finishes. You can use the keyring package to avoid passwords inplain files.
See Also
Other R CMD commands: rcmd_bg(), rcmd()
rcmd_process External R CMD Process
Description
An R CMD * command that runs in the background. This is an R6 class that extends the pro-cessx::process class.
Super class
processx::process -> rcmd_process
Methods
Public methods:• rcmd_process$new()
• rcmd_process$finalize()
• rcmd_process$clone()
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.
rcmd_process_options 13
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()
rcmd_process_options 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_processclass. 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 selectthe R CMD subcommand to run. Typically cmdargs is specified as well, to supply more argumentsto R CMD.
Examples
## List all options and their default values:rcmd_process_options()
14 rscript
rcmd_safe_env rcmd_safe_env returns a set of environment variables that are moreappropriate for rcmd_safe(). It is exported to allow manipulatingthese variables (e.g. add an extra one), before passing them to thercmd() functions.
Description
It currently has the following variables:
• CYGWIN="nodosfilewarning": On Windows, do not warn about MS-DOS style file names.
• R_TESTS="" This variable is set by R CMD check, and makes the child R process load a startupfile at startup, from the current working directory, that is assumed to be the /test directory ofthe package being checked. If the current working directory is changed to something else (asit typically is by testthat, then R cannot start. Setting it to the empty string ensures thatcallr can be used from unit tests.
• R_BROWSER="false": typically we don’t want to start up a browser from the child R process.
• R_PDFVIEWER="false": similarly for the PDF viewer.
Usage
rcmd_safe_env()
Details
Note that callr also sets the R_ENVIRON, R_ENVIRON_USER, R_PROFILE and R_PROFILE_USER en-vironment 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.
rscript Run an R script
Description
It uses the Rscript program corresponding to the current R version, to run the script. It streamsstdout and stderr of the process.
rscript 15
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 onlyused if user_profile or system_profile is set FALSE, as it is set using thesystem 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 asstdout, in which case standard error is redirected to standard output. It can alsobe the special string "2>&1", in which case standard error will be redirected tostandard output.
poll_connection
Whether to have a control connection to the process. This is used to transmitmessages 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 pro-cess is running. Note that this is independent of the stdout and stderr argu-ments. The standard error is not shown currently.
callback A function to call for each line of the standard output and standard error from thechild process. It works together with the show option; i.e. if show = TRUE, and a
16 rscript_process
callback is provided, then the output is shown of the screen, and the callback isalso called.
block_callback A function to call for each block of the standard output and standard error. Thiscallback is not line oriented, i.e. multiple lines or half a line can be passed to thecallback.
spinner Whether to show a calming spinner on the screen while the child R session isrunning. 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 pro-file from the working directory is used, but the R_PROFILE_USER environmentvariable 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 areal number, meaning seconds. If the process does not finish before the timeoutperiod expires, then a system_command_timeout_error error is thrown. Infmeans no timeout.
wd Working directory to use for running the command. Defaults to the currentworking 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 inthe 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 yourenvironment file or your profile, otherwise this information will get scattered in various files, at leasttemporarily, until the subprocess finishes. You can use the keyring package to avoid passwords inplain files.
rscript_process External Rscript process
Description
An Rscript script.R command that runs in the background. This is an R6 class that extends theprocessx::process class.
Super class
processx::process -> rscript_process
rscript_process_options 17
Methods
Public methods:
• rscript_process$new()
• rscript_process$finalize()
• rscript_process$clone()
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()
rscript_process_options
Create options for an rscript_process object
Description
Create options for an rscript_process object
Usage
rscript_process_options(...)
18 r_bg
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_processclass. 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()
r_bg 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.
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,...
)
r_bg 19
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 fromother packages using the :: notation. The environment of the function is set to.GlobalEnv before passing it to the child process. Because of this, it is goodpractice to create an anonymous function and pass that to callr, instead ofpassing 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 onlyused if user_profile or system_profile is set FALSE, as it is set using thesystem or the user profile.
stdout The name of the file the standard output of the child R process will be writtento. If the child process runs with the --slave option (the default), then the com-mands are not echoed and will not be shown in the standard output. Also notethat you need to call print() explicitly to show the output of the command(s).
stderr The name of the file the standard error of the child R process will be writtento. In particular message() sends output to the standard error. If nothing wassent to the standard error, then this file will be empty. This argument can be thesame file as stdout, in which case they will be correctly interleaved. If this isthe string "2>&1", then standard error is redirected to standard output.
poll_connection
Whether to have a control connection to the process. This is used to transmitmessages 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 containsa 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 pro-file from the working directory is used, but the R_PROFILE_USER environmentvariable 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 willensure that the process is killed when the R process exits.
... Extra arguments are passed to the processx::process constructor.
20 r_copycat
Value
An r_process object, which inherits from process, so all process methods can be called on it, andin 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 yourenvironment file or your profile, otherwise this information will get scattered in various files, at leasttemporarily, until the subprocess finishes. You can use the keyring package to avoid passwords inplain files.
Examples
rx <- r_bg(function() 1 + 2)
# wait until it is donerx$wait()rx$is_alive()rx$get_result()
r_copycat Run an R process that mimics the current R process
Description
Differences to r():
• No extra repositories are set up.
• The --no-save, --no-restore command line arguments are not used. (But --slave still is.)
• The system profile and the user profile are loaded.
• No extra environment variables are set up.
Usage
r_copycat(func,args = list(),libpath = .libPaths(),repos = getOption("repos"),cmdargs = "--slave",system_profile = TRUE,user_profile = TRUE,env = character(),...
)
r_copycat 21
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 fromother packages using the :: notation. The environment of the function is set to.GlobalEnv before passing it to the child process. Because of this, it is goodpractice to create an anonymous function and pass that to callr, instead ofpassing 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 onlyused if user_profile or system_profile is set FALSE, as it is set using thesystem 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 containsa 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 pro-file from the working directory is used, but the R_PROFILE_USER environmentvariable 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 yourenvironment file or your profile, otherwise this information will get scattered in various files, at leasttemporarily, until the subprocess finishes. You can use the keyring package to avoid passwords inplain files.
See Also
Other callr functions: r_vanilla(), r()
22 r_process
r_process External R Process
Description
An R process that runs in the background. This is an R6 class that extends the processx::processclass. The process starts in the background, evaluates an R function call, and then quits.
Super class
processx::process -> r_process
Methods
Public methods:• r_process$new()
• r_process$get_result()
• r_process$finalize()
• r_process$clone()
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 pro-cessx::process) to wait for the process to finish, optionally with a timeout.) You can also useprocessx::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 isgarbage 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.
r_process_options 23
Examples
## List all options and their default values:r_process_options()
## Start an R process in the background, wait for it, get resultopts <- r_process_options(func = function() 1 + 1)rp <- r_process$new(opts)rp$wait()rp$get_result()
r_process_options 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 theR function to run in the background.
Examples
## List all options and their default values:r_process_options()
24 r_session
r_session External R Session
Description
A permanent R session that runs in the background. This is an R6 class that extends the pro-cessx::process class.
The process is started at the creation of the object, and then it can be used to evaluate R functioncalls, one at a time.
Super class
processx::process -> r_session
Methods
Public methods:• r_session$new()
• r_session$run()
• r_session$run_with_output()
• r_session$call()
• r_session$poll_process()
• r_session$get_state()
• r_session$get_running_time()
• r_session$read()
• r_session$close()
• r_session$traceback()
• r_session$debug()
• r_session$attach()
• r_session$finalize()
• r_session$print()
• r_session$clone()
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 caseyou 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.
r_session 25
Method run(): Similar to r(), but runs the function in a permanent background R session. Itthrows an error if the function call generated an error in the child process.
Usage:r_session$run(func, args = list())
Arguments:
func Function object to call in the background R process. Please read the notes for the similarargument of r().
args Arguments to pass to the function. Must be a list.
Returns: The return value of the R expression.
Method run_with_output(): Similar to $run(), but returns the standard output and error of thechild process as well. It does not throw on errors, but returns a non-NULL error member in theresult list.
Usage:r_session$run_with_output(func, args = list())
Arguments:
func Function object to call in the background R process. Please read the notes for the similarargument of r().
args Arguments to pass to the function. Must be a list.
Returns: A list with the following entries.• result: The value returned by func. On error this is NULL.• stdout: The standard output of the process while evaluating• stderr: The standard error of the process while evaluating the func call.• error: On error it contains an error object, that contains the error thrown in the subprocess.
Otherwise it is NULL.• code, message: These fields are used by call internally and you can ignore them.
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())
Arguments:
func Function object to call in the background R process. Please read the notes for the similarargument of r().
args Arguments to pass to the function. Must be a list.
Method poll_process(): Poll the R session with a timeout. If the session has finished thecomputation, 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.
26 r_session
Returns: Character string "ready" or "timeout".
Method get_state(): Return the state of the R session.
Usage:r_session$get_state()
Returns: Possible values:• "starting": starting up,• "idle": ready to compute,• "busy": computing right now,• "finished": the R process has finished.
Method get_running_time(): Returns the elapsed time since the R process has started, andthe elapsed time since the current computation has started. The latter is NA if there is no activecomputation.
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 mightsignal 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_resultobject. The list always has a code entry which is the type of the event. Event types:
• 200: The computation is done, and the event includes the result, in the same form as for therun() method.
• 201: An R session that was in ’starting’ state is ready to go.• 202: Used by the attach() method.• 301: A message from the subprocess. The message is a condition object with class callr_message.
(It typically has other classes, e.g. cli_message for output from the cli package.• 500: The R session finished cleanly. This means that the evaluated expression quit R.• 501: The R session crashed or was killed.• 502: The R session closed its end of the connection that callr uses for communication.
Method close(): Terminate the current computation and the R process. The session object willbe 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 standardinput is closed. If the process is still running after this period, it will be killed.
r_session 27
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.
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 anerror. See more at r_session_debug.
Usage:r_session$debug()
Method attach(): Experimental function that provides a REPL (Read-Eval-Print-Loop) to thesubprocess.
Usage:r_session$attach()
Method finalize(): Finalizer that is called when garbage collecting an r_session object, toclean 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()
28 r_session_debug
r_session_debug Interactive debugging of persistent R sessions
Description
The r_session$debug() method is an interactive debugger to inspect the stack of the backgroundprocess after an error.
Details$debug() starts a REPL (Read-Eval-Print-Loop), that evaluates R expressions in the subprocess. Itis similar to browser() and debugger() and also has some extra commands:
• .help prints a short help message.
• .where prints the complete stack trace of the error. (The same as the $traceback() method.• .inspect <n> switches the "focus" to frame <n>. Frame 0 is the global environment, so .in-
spect 0 will switch back to that.
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
r_session_options 29
[1] "no-such-file"
RS 87361 (frame 1) > file.exists(input)[1] FALSE
RS 87361 (frame 1) > # <CTRL + C># ----------------------------------------------------------------------
r_session_options 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.
r_vanilla Run an R child process, with no configuration
Description
It tries to mimic a fresh R installation. In particular:
• No library path setting.• No CRAN(-like) repository is set.• The system and user profiles are not run.
Usage
r_vanilla(func,args = list(),libpath = character(),repos = c(CRAN = "@CRAN@"),cmdargs = "--slave",system_profile = FALSE,user_profile = "project",env = character(),...
)
30 r_vanilla
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 fromother packages using the :: notation. The environment of the function is set to.GlobalEnv before passing it to the child process. Because of this, it is goodpractice to create an anonymous function and pass that to callr, instead ofpassing 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 onlyused if user_profile or system_profile is set FALSE, as it is set using thesystem 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 containsa 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 pro-file from the working directory is used, but the R_PROFILE_USER environmentvariable 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 yourenvironment file or your profile, otherwise this information will get scattered in various files, at leasttemporarily, until the subprocess finishes. You can use the keyring package to avoid passwords inplain files.
See Also
Other callr functions: r_copycat(), r()
Examples
# Compare to r()r(function() .libPaths())
r_vanilla 31
r_vanilla(function() .libPaths())
r(function() getOption("repos"))r_vanilla(function() getOption("repos"))
Index
base::difftime, 5, 9, 16base::traceback(), 27browser(), 28
callr, 2callr-package (callr), 2
debugger(), 28default_repos, 3
process, 11, 20processx::poll(), 22processx::process, 11, 12, 16, 19, 22, 24processx::run(), 5, 9, 16
r, 3, 21, 30r(), 20, 21, 23, 25, 30r_bg, 18r_copycat, 6, 20, 30r_copycat(), 6r_process, 22, 23r_process_options, 23r_process_options(), 22r_safe (r), 3r_session, 24, 29r_session_debug, 27, 28r_session_options, 29r_session_options(), 24r_vanilla, 6, 21, 29rcmd, 7, 11, 12rcmd(), 11–14rcmd_bg, 9, 9, 12rcmd_copycat, 9, 11, 11rcmd_copycat(), 9rcmd_process, 12, 13rcmd_process_options, 13rcmd_process_options(), 12rcmd_safe (rcmd), 7rcmd_safe(), 14rcmd_safe_env, 14
rcmd_safe_env(), 3rscript, 14rscript(), 18rscript_process, 16, 17rscript_process_options, 17rscript_process_options(), 17
utils::debugger(), 6utils::dump.frames(), 6
32