Movatterモバイル変換


[0]ホーム

URL:


Package 'callr'

Title: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.
Authors:Gábor Csárdi [aut, cre, cph] (ORCID: <https://orcid.org/0000-0001-7098-9676>), Winston Chang [aut], Posit Software, PBC [cph, fnd] (ROR: <https://ror.org/03wc8by49>), Ascent Digital Services [cph, fnd]
Maintainer:Gábor Csárdi <[email protected]>
License:MIT + file LICENSE
Version:3.7.6.9000
Built:2025-11-20 06:45:47 UTC
Source:https://github.com/r-lib/callr

Help Index


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

Description

This function allows users ofcallr to specify functions that get invokedwhenever an R session is launched. The function can modify the environmentvariables and command line arguments.

Usage

add_hook(...)

Arguments

...

Named argument specifying a hook function to add, orNULL todelete the named hook.

Details

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

Value

add_hook is called for its side-effects.


Default value for therepos option in callr subprocesses

Description

callr sets therepos option in subprocesses, to make sure thata CRAN mirror is set up. This is because the subprocess cannot bringup the menu of CRAN mirrors for the user to choose from.

Usage

default_repos()

Value

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

Examples

default_repos()

Evaluate an expression in another R session

Description

Fromcallr version 2.0.0,r() is equivalent tor_safe(), andtries to set up a less error prone execution environment. In particular:

  • Ensures that at least one reasonable CRAN mirror is set up.

  • Adds some command line arguments to avoid saving.RData files, etc.

  • Ignores the system and user profiles (by default).

  • Sets various environment variables:CYGWIN to avoidwarnings about DOS-style paths,R_TESTS to avoid issueswhencallr is invoked from unit tests,R_BROWSERandR_PDFVIEWER to avoid starting a browser or a PDF viewer.Seercmd_safe_env().

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 toother functions and use variables explicitly from other packagesusing the:: notation. By default the environment of the functionis set to.GlobalEnv before passing it to the child process.(See thepackage option if you want to keep the environment.)Because of this, it is good practice to create an anonymousfunction and pass that tocallr, instead of passinga function object from a (base or other) package. In particular

r(.libPaths)

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

r(function() .libPaths())

works just fine.

args

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

libpath

The library path.

repos

Therepos option. IfNULL, then norepos option is set. This options is only used ifuser_profile orsystem_profile is setFALSE,as it is set using the system or the user profile.

stdout

The name of the file the standard output ofthe 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 shownin the standard output. Also note that you need to callprint()explicitly to show the output of the command(s).IFNULL, then standard output is not returned, butit is recorded and included in the error object if an error happens.Various special values for this argument such as"|" are explainedin thestdout argument ofprocessx::process.

stderr

The name of the file the standard error ofthe child R process will be written to.In particularmessage() sends output to the standarderror. If nothing was sent to the standard error, then this filewill be empty. This argument can be the same file asstdout,in which case they will be correctly interleaved. If this is thestring"2>&1", then standard error is redirected to standard output.IFNULL, then standard output is not returned, butit is recorded and included in the error object if an error happens.Various special values for this argument such as"|" are explainedin thestdout argument ofprocessx::process.

poll_connection

Whether to have a control connection tothe process. This is used to transmit messages from the subprocessto 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 thatc("-f", rscript) is appended to this,rscriptis the name of the script file to run. This contains a call to thesupplied function and some error handling code.

show

Logical, whether to show the standard output on the screenwhile the child process is running. Note that this is independentof thestdout andstderr arguments. The standarderror is not shown currently.

callback

A function to call for each line of the standardoutput and standard error from the child process. It works togetherwith theshow option; i.e. ifshow = TRUE, and acallback is provided, then the output is shown of the screen, and thecallback is also called.

block_callback

A function to call for each block of the standardoutput 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 whilethe child R session is running. By default it is shown ifshow = 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 workingdirectory is used, but theR_PROFILE_USER environment variableand 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 abase::difftime object, or a real number, meaning seconds.If the process does not finish before the timeout period expires,then asystem_command_timeout_error error is thrown.Infmeans no timeout.

package

Whether to keep the environment offunc when passingit 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 thepkg package namespace.

arch

Architecture to use in the child process, for multi-archbuilds of R. By default the same as the main process. Seesupported_archs(). If it contains a forward or backward slashcharacter, then it is taken as the path to the R executable.Note that on Windows you need the path toRterm.exe.

...

Extra arguments are passed toprocessx::run().

Details

Ther() function from before 2.0.0 is calledr_copycat() now.

Value

Value of the evaluated expression.

Error handling

callr handles errors properly. If the child process throws anerror, thencallr throws an error with the same error messagein the main process.

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

  • error is the default behavior: throw an error in the main process,with a prefix and the same error message as in the subprocess.

  • stack also throws an error in the main process, but the erroris of a special kind, classcallr_error, and it containsboth the original error object, and the call stack of the child,as written out byutils::dump.frames(). This is now deprecated,because the error thrown for"error" has the same information.

  • debugger is similar tostack, but in additionto returning the complete call stack, it also start up a debuggerin the child call stack, viautils::debugger().

The default error behavior can be also set using thecallr.erroroption. This is useful to debug code that usescallr.

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

Security considerations

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

Transporting objects

func andargs are copied to the child process by first serializing theminto a temporary file usingsaveRDS() and then loading them back into thechild session usingreadRDS(). The same strategy is used to copy the resultof callingfunc(args) to the main session. Note that some objects, notablythose withexternalptr type, won't work as expected after beingsaved to a file and loaded back.

For performance reasonscompress=FALSE is used when serializing withsaveRDS(), this can be disabled by settingoptions(callr.compress_transport = TRUE).

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()

Evaluate an expression in another R session, in the background

Description

Starts evaluating an R function call in a background R process, andreturns immediately.Usep$get_result() to collect the result or to throw an errorif 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 toother functions and use variables explicitly from other packagesusing the:: notation. By default the environment of the functionis set to.GlobalEnv before passing it to the child process.(See thepackage option if you want to keep the environment.)Because of this, it is good practice to create an anonymousfunction and pass that tocallr, instead of passinga function object from a (base or other) package. In particular

r(.libPaths)

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

r(function() .libPaths())

works just fine.

args

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

libpath

The library path.

repos

Therepos option. IfNULL, then norepos option is set. This options is only used ifuser_profile orsystem_profile is setFALSE,as it is set using the system or the user profile.

stdout

The name of the file the standard output ofthe 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 shownin the standard output. Also note that you need to callprint()explicitly to show the output of the command(s).IFNULL, then standard output is not returned, butit is recorded and included in the error object if an error happens.Various special values for this argument such as"|" are explainedin thestdout argument ofprocessx::process.

stderr

The name of the file the standard error ofthe child R process will be written to.In particularmessage() sends output to the standarderror. If nothing was sent to the standard error, then this filewill be empty. This argument can be the same file asstdout,in which case they will be correctly interleaved. If this is thestring"2>&1", then standard error is redirected to standard output.IFNULL, then standard output is not returned, butit is recorded and included in the error object if an error happens.Various special values for this argument such as"|" are explainedin thestdout argument ofprocessx::process.

poll_connection

Whether to have a control connection tothe process. This is used to transmit messages from the subprocessto 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 thatc("-f", rscript) is appended to this,rscriptis the name of the script file to run. This contains a call to thesupplied 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 workingdirectory is used, but theR_PROFILE_USER environment variableand 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. IfTRUE,the supervisor will ensure that the process is killed when the R processexits.

package

Whether to keep the environment offunc when passingit 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 thepkg package namespace.

arch

Architecture to use in the child process, for multi-archbuilds of R. By default the same as the main process. Seesupported_archs(). If it contains a forward or backward slashcharacter, then it is taken as the path to the R executable.Note that on Windows you need the path toRterm.exe.

...

Extra arguments are passed to theprocessx::processconstructor.

Value

Anr_process object, which inherits fromprocess,so allprocess methods can be called on it, and in addition it alsohas aget_result() method to collect the result.

Security considerations

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

Examples

rx<- r_bg(function()1+2)# wait until it is donerx$wait()rx$is_alive()rx$get_result()

Run an R process that mimics the current R process

Description

Differences tor():

  • No extra repositories are set up.

  • The--no-save,--no-restorecommand 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(),...)

Arguments

func

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

r(.libPaths)

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

r(function() .libPaths())

works just fine.

args

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

libpath

The library path.

repos

Therepos option. IfNULL, then norepos option is set. This options is only used ifuser_profile orsystem_profile is setFALSE,as it is set using the system or the user profile.

cmdargs

Command line arguments to pass to the R process.Note thatc("-f", rscript) is appended to this,rscriptis the name of the script file to run. This contains a call to thesupplied 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 workingdirectory is used, but theR_PROFILE_USER environment variableand the user level profile are not. See also "Security considerations"below.

env

Environment variables to set for the child process.

...

Additional arguments are passed tor().

Security considerations

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

See Also

Other callr functions:r(),r_vanilla()


External R Process

Description

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

Super class

processx::process ->r_process

Methods

Public methods

Inherited methods

Methodnew()

Start a new R process in the background.

Usage
r_process$new(options)
Arguments
options

A list of options created viar_process_options().

Returns

A newr_process object.


Methodget_result()

Return the result, an R object, from a finishedbackground R process. If the process has not finished yet, it throwsan error. (You can usewait() method (seeprocessx::process) towait for the process to finish, optionally with a timeout.) You canalso 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 Rprocess.


Methodclone()

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 resultopts<- r_process_options(func=function()1+1)rp<- r_process$new(opts)rp$wait()rp$get_result()

Create options for anr_process object

Description

Create options for anr_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 newobject from ther_process class. Its arguments must be named, thenames are used as option names. The options correspond to (some of)the arguments of ther() function. At least thefunc option must bespecified, 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 classthat extends theprocessx::process class.

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

Super class

processx::process ->r_session

Public fields

status

Status codes returned byread().

Methods

Public methods

Inherited methods

Methodnew()

creates a new R background process. It can wait for the process tostart up (wait = TRUE), or return immediately, i.e. beforethe process is actually ready to run. In the latter case you may callthepoll_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 viar_session_options().

wait

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

wait_timeout

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

Returns

Anr_session object.


Methodrun()

Similar tor(), but runs the function in a permanent backgroundR session. It throws an error if the function call generated anerror 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 ofr().

args

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

package

Whether to keep the environment offunc when passingit 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 thepkg package namespace.

Returns

The return value of the R expression.


Methodrun_with_output()

Similar to⁠$run()⁠, but returns the standard output and error ofthe child process as well. It does not throw on errors, butreturns a non-NULLerror 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 ofr().

args

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

package

Whether to keep the environment offunc when passingit 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 thepkg package namespace.

Returns

A list with the following entries.

  • result: The value returned byfunc. On error this isNULL.

  • stdout: The standard output of the process while evaluating

  • stderr: The standard error of the process while evaluatingthefunc call.

  • error: On error it contains an error object, that contains theerror thrown in the subprocess. Otherwise it isNULL.

  • code,message: These fields are used by call internally andyou can ignore them.


Methodcall()

Starts running a function in the background R session, andreturns immediately. To check if the function is done, call thepoll_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 ofr().

args

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

package

Whether to keep the environment offunc when passingit 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 thepkg package namespace.


Methodpoll_process()

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

Usage
r_session$poll_process(timeout)
Arguments
timeout

Timeout period in milliseconds.

Returns

Character string"ready" or"timeout".


Methodget_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.


Methodget_running_time()

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

Usage
r_session$get_running_time()
Returns

Named vector ofPOSIXct objects. The names are"total"and"current".


Methodread()

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

This is a low level function that you only need to use if youwant 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 acallr_session_result object. The list always hasacode entry which is the type of the event. See alsor_session$public_fields$status for symbolic names of theevent types.

  • 200: (DONE) The computation is done, and the event includesthe result, in the same form as for therun() method.

  • 201: (STARTED) An R session that was in 'starting' state isready to go.

  • 202: (ATTACH_DONE) Used by theattach() method.

  • 301: (MSG) A message from the subprocess. The message is acondition object with classcallr_message. (It typically hasother classes, e.g.cli_message for output from the clipackage.)

  • 500: (EXITED) The R session finished cleanly. This meansthat the evaluated expression quit R.

  • 501: (CRASHED) The R session crashed or was killed.

  • 502: (CLOSED) The R session closed its end of the connectionthat callr uses for communication.


Methodclose()

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 thesubprocess to exit cleanly, after its standard input is closed.If the process is still running after this period, it will bekilled.


Methodtraceback()

Thetraceback() method can be used after an error in the Rsubprocess. It is equivalent to thebase::traceback() call, inthe subprocess.

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

Usage
r_session$traceback()
Returns

The same output as frombase::traceback()


Methoddebug()

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

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

Usage
r_session$debug()

Methodattach()

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

Usage
r_session$attach()

Methodprint()

Print method for anr_session.

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

Arguments are not used currently.


Methodclone()

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_session$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

Ther_session$debug() method is an interactive debugger to inspectthe stack of the background process after an error.

Details

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

⁠$debug()⁠ starts a REPL (Read-Eval-Print-Loop), that evaluates Rexpressions in the subprocess. It is similar tobrowser() anddebugger() and also has some extra commands:

  • .help prints a short help message.

  • .where prints the complete stack trace of the error. (The same asthe⁠$traceback()⁠ method.

  • ⁠.inspect <n>⁠ switches the "focus" to frame⁠<n>⁠. Frame 0 is theglobal environment, so⁠.inspect 0⁠ will switch back to that.

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

Here is an example session that uses⁠$debug()⁠ (some output is omittedfor 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 .GlobalEnv3: file(con, "r")2: readLines(input2, encoding = "UTF-8", warn = FALSE)1: knitr::knit("no-such-file") at #1RS 87361 > .inspect 1RS 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] FALSERS 87361 (frame 1) > # <CTRL + C># ----------------------------------------------------------------------

Create options for anr_session object

Description

Create options for anr_session object

Usage

r_session_options(...)

Arguments

...

Options to override, named arguments.

Value

Named list of options.

The current options are:

  • libpath: Library path for the subprocess. By default the same as thecurrent library path. I.e.not necessarily the library path ofa fresh R session.)

  • repos:repos option for the subprocess. By default the currentvalue of the main process.

  • stdout: Standard output of the sub-process. This can beNULL ora pipe:"|". If it is a pipe then the output of the subprocess isnot included in the responses, but you need to poll and read itmanually. This is for experts. Note that this option is not usedfor the startup phase that currently always runs withstdout = "|".

  • stderr: Similar tostdout, but for the standard error. Likestdout, it is not used for the startup phase, which runs withstderr = "|".

  • error: See 'Error handling' inr().

  • cmdargs: See the same argument ofr(). (Its default might bedifferent, though.)

  • system_profile: See the same argument ofr().

  • user_profile: See the same argument ofr().

  • env: See the same argument ofr().

  • load_hook:NULL, or code (quoted) to run in the sub-processat start up. (I.e. not for every singlerun() call.)

  • extra: List of extra arguments to pass toprocessx::process.

Callr_session_options() to see the default values.r_session_options() might contain undocumented entries, you cannotchange these.

Examples

r_session_options()

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=FALSE,  env= character(),...)

Arguments

func

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

r(.libPaths)

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

r(function() .libPaths())

works just fine.

args

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

libpath

The library path.

repos

Therepos option. IfNULL, then norepos option is set. This options is only used ifuser_profile orsystem_profile is setFALSE,as it is set using the system or the user profile.

cmdargs

Command line arguments to pass to the R process.Note thatc("-f", rscript) is appended to this,rscriptis the name of the script file to run. This contains a call to thesupplied 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 workingdirectory is used, but theR_PROFILE_USER environment variableand the user level profile are not. See also "Security considerations"below.

env

Environment variables to set for the child process.

...

Additional arguments are passed tor().

Security considerations

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

See Also

Other callr functions:r(),r_copycat()

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 startanother 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. SeeR --help from the commandline 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

Therepos option. IfNULL, then norepos option is set. This options is only used ifuser_profile orsystem_profile is setFALSE,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 asstdout, in which case standard error isredirected to standard output. It can also be the special string"2>&1", in which case standard error will be redirected to standardoutput.

poll_connection

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

echo

Whether to echo the complete command run byrcmd.

show

Logical, whether to show the standard output on the screenwhile the child process is running. Note that this is independentof thestdout andstderr arguments. The standarderror is not shown currently.

callback

A function to call for each line of the standardoutput and standard error from the child process. It works togetherwith theshow option; i.e. ifshow = TRUE, and acallback is provided, then the output is shown of the screen, and thecallback is also called.

block_callback

A function to call for each block of the standardoutput 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 whilethe child R session is running. By default it is shown ifshow = 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 workingdirectory is used, but theR_PROFILE_USER environment variableand 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 abase::difftime object, or a real number, meaning seconds.If the process does not finish before the timeout period expires,then asystem_command_timeout_error error is thrown.Infmeans no timeout.

wd

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

fail_on_status

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

...

Extra arguments are passed toprocessx::run().

Details

Starting fromcallr 2.0.0,rcmd() has safer defaults, the same asthercmd_safe() default values. Usercmd_copycat() for the olddefaults.

Value

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

Security considerations

callr makes a copy of the user's.Renviron file and potentially ofthe local or user.Rprofile, in the session temporarydirectory. Avoid storing sensitive information such as passwords, inyour environment file or your profile, otherwise this information willget scattered in various files, at least temporarily, until thesubprocess finishes. You can use the keyring package to avoid passwordsin 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 functionreturn 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. SeeR --help from the commandline 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 asstdout, in which case standard error isredirected to standard output. It can also be the special string"2>&1", in which case standard error will be redirected to standardoutput.

poll_connection

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

repos

Therepos option. IfNULL, then norepos option is set. This options is only used ifuser_profile orsystem_profile is setFALSE,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 workingdirectory is used, but theR_PROFILE_USER environment variableand 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. Defaultsto the current working directory.

supervise

Whether to register the process with a supervisor. IfTRUE,the supervisor will ensure that the process is killed when the R processexits.

...

Extra arguments are passed to theprocessx::processconstructor.

Value

It returns aprocess object.

Security considerations

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

See Also

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


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

Description

This function is similar torcmd(), but it has slightly differentdefaults:

  • Therepos 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. SeeR --help from the commandline 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

Therepos option. IfNULL, then norepos option is set. This options is only used ifuser_profile orsystem_profile is setFALSE,as it is set using the system or the user profile.

env

Environment variables to set for the child process.

...

Additional arguments are passed torcmd().

Security considerations

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

See Also

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


External⁠R CMD⁠ Process

Description

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

Super class

processx::process ->rcmd_process

Methods

Public methods

Inherited methods

Methodnew()

Start an⁠R CMD⁠ process.

Usage
rcmd_process$new(options)
Arguments
options

A list of options created viarcmd_process_options().

Returns

A newrcmd_process object.


Methodclone()

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 anrcmd_process object

Description

Create options for anrcmd_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 newobject from thercmd_process class. Its arguments must be named, thenames are used as option names. The options correspond to (some of)the arguments of thercmd() function. At least thecmd option mustbe specified, to select the⁠R CMD⁠ subcommand to run. Typicallycmdargs 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 aremore appropriate forrcmd_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-DOSstyle file names.

  • R_TESTS="" This variable is set by⁠R CMD check⁠, and makes thechild R process load a startup file at startup, from the currentworking directory, that is assumed to be the⁠/test⁠ directoryof the package being checked. If the current working directory ischanged to something else (as it typically is bytestthat, then Rcannot start. Setting it to the empty string ensures thatcallr canbe used from unit tests.

  • R_BROWSER="false": typically we don't want to start up a browserfrom the child R process.

  • R_PDFVIEWER="false": similarly for the PDF viewer.

Usage

rcmd_safe_env()

Details

Note thatcallr also sets theR_ENVIRON,R_ENVIRON_USER,R_PROFILE andR_PROFILE_USER environment variablesappropriately, unless these are set by the user in theenv argumentof ther, etc. calls.

Value

A named character vector of environment variables.


Run an R script

Description

It uses theRscript program corresponding to the current R version,to run the script. It streamsstdout andstderr 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

Therepos option. IfNULL, then norepos option is set. This options is only used ifuser_profile orsystem_profile is setFALSE,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 asstdout, in which case standard error isredirected to standard output. It can also be the special string"2>&1", in which case standard error will be redirected to standardoutput.

poll_connection

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

echo

Whether to echo the complete command run byrcmd.

show

Logical, whether to show the standard output on the screenwhile the child process is running. Note that this is independentof thestdout andstderr arguments. The standarderror is not shown currently.

callback

A function to call for each line of the standardoutput and standard error from the child process. It works togetherwith theshow option; i.e. ifshow = TRUE, and acallback is provided, then the output is shown of the screen, and thecallback is also called.

block_callback

A function to call for each block of the standardoutput 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 whilethe child R session is running. By default it is shown ifshow = 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 workingdirectory is used, but theR_PROFILE_USER environment variableand 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 abase::difftime object, or a real number, meaning seconds.If the process does not finish before the timeout period expires,then asystem_command_timeout_error error is thrown.Infmeans no timeout.

wd

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

fail_on_status

Whether to throw an R error if the command returnswith 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 toprocessx::run().

Security considerations

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


ExternalRscript process

Description

An⁠Rscript script.R⁠ command that runs in the background. This is anR6 class that extends theprocessx::process class.

Super class

processx::process ->rscript_process

Methods

Public methods

Inherited methods

Methodnew()

Create a newRscript process.

Usage
rscript_process$new(options)
Arguments
options

A list of options created viarscript_process_options().


Methodclone()

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 anrscript_process object

Description

Create options for anrscript_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 newobject from therscript_process class. Its arguments must be named,the names are used as option names. The options correspond to (some of)the arguments of therscript() function. At least thescript optionmust 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 resultshould be taken as a best guess.

Usage

supported_archs()

Value

Character vector of supported architectures. If thecurrent R build is not a multi-architecture build, then an emptystring scalar is returned.

Examples

supported_archs()


[8]ページ先頭

©2009-2025 Movatter.jp