% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/callr-package.R
\docType{package}
\name{callr-package}
\alias{callr}
\alias{callr-package}
\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.
}
\section{callr}{
\subsection{Features}{
\itemize{
\item Calls an R function, with arguments, in a subprocess.
\item Copies function arguments to the subprocess and copies the return value of the function back, seamlessly.
\item Copies error objects back from the subprocess, including a stack trace.
\item Shows and/or collects the standard output and standard error of the subprocess.
\item Supports both one-off and persistent R subprocesses.
\item Calls the function synchronously or asynchronously (in the background).
\item Can call \verb{R CMD} commands, synchronously or asynchronously.
\item Can call R scripts, synchronously or asynchronously.
\item Provides extensible \code{r_process}, \code{rcmd_process} and \code{rscript_process} R6 classes, based on \code{processx::process}.
\item Emits \href{https://opentelemetry.io/}{OpenTelemetry} traces for every R subprocess and propagates trace context across the process boundary.
}
}

\subsection{Installation}{

Install the stable version from CRAN:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{install.packages("callr")
}\if{html}{\out{</div>}}

Install the development version from GitHub:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{pak::pak("r-lib/callr")
}\if{html}{\out{</div>}}
}

\subsection{Synchronous, one-off R processes}{

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

\if{html}{\out{<div class="sourceCode r">}}\preformatted{callr::r(function() var(iris[, 1:4]))
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#>              Sepal.Length Sepal.Width Petal.Length Petal.Width                  
#> Sepal.Length    0.6856935  -0.0424340    1.2743154   0.5162707                  
#> Sepal.Width    -0.0424340   0.1899794   -0.3296564  -0.1216394                  
#> Petal.Length    1.2743154  -0.3296564    3.1162779   1.2956094                  
#> Petal.Width     0.5162707  -0.1216394    1.2956094   0.5810063                  
</pre></div>
}}

\subsection{Passing arguments}{

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

\if{html}{\out{<div class="sourceCode r">}}\preformatted{mycars <- cars
callr::r(function() summary(mycars))
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#> Error:                                                                          
#> ! in callr subprocess.                                                          
#> Caused by error in `(function () ...`:                                          
#> ! object 'mycars' not found                                                     
#> Type .Last.error to see the more details.                                       
</pre></div>
}}


But this does:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{mycars <- cars
callr::r(function(x) summary(x), args = list(mycars))
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#>      speed           dist                                                       
#>  Min.   : 4.0   Min.   :  2.00                                                  
#>  1st Qu.:12.0   1st Qu.: 26.00                                                  
#>  Median :15.0   Median : 36.00                                                  
#>  Mean   :15.4   Mean   : 42.98                                                  
#>  3rd Qu.:19.0   3rd Qu.: 56.00                                                  
#>  Max.   :25.0   Max.   :120.00                                                  
</pre></div>
}}


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

\subsection{Using packages}{

You can use any R package in the child process, just make sure to refer to it explicitly with the \code{::} operator.
For example, the following code creates an \href{https://github.com/igraph/rigraph}{igraph} graph in the child, and calculates some metrics of it.

\if{html}{\out{<div class="sourceCode r">}}\preformatted{callr::r(function() \{ g <- igraph::sample_gnp(1000, 4/1000); igraph::diameter(g) \})
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#> [1] 11                                                                          
</pre></div>
}}

}

\subsection{Error handling}{

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

\if{html}{\out{<div class="sourceCode r">}}\preformatted{callr::r(function() 1 + "A")
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#> Error:                                                                          
#> ! in callr subprocess.                                                          
#> Caused by error in `1 + "A"`:                                                   
#> ! non-numeric argument to binary operator                                       
#> Type .Last.error to see the more details.                                       
</pre></div>
callr sets the `.Last.error` variable, and after an error you can inspect this for more details about the error, including stack traces both from the main R process and the subprocess.
}}


\if{html}{\out{<div class="sourceCode r">}}\preformatted{.Last.error
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#> Error:                                                                          
#> ! in callr subprocess.                                                          
#> Caused by error in `1 + "A"`:                                                   
#> ! non-numeric argument to binary operator                                       
#> ---                                                                             
#> Backtrace:                                                                      
#> 1. callr::r(function() 1 + "A")                                                 
#> 2. callr:::get_result(output = out, options)                                    
#> 3. callr:::throw(callr_remote_error(remerr, output), parent = fix_msg(remerr[[3]
#> ]))                                                                             
#> ---                                                                             
#> Subprocess backtrace:                                                           
#> 1. base::.handleSimpleError(function (e)                                        
#> 2. global h(simpleError(msg, call))                                             
</pre></div>
}}


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

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

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

\subsection{Standard output and error}{

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

\if{html}{\out{<div class="sourceCode r">}}\preformatted{x <- callr::r(function() \{ print("hello world!"); message("hello again!") \},
  stdout = "/tmp/out", stderr = "/tmp/err"
)
readLines("/tmp/out")
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#> [1] "[1] \\"hello world!\\""                                                      
</pre></div>
}}


\if{html}{\out{<div class="sourceCode r">}}\preformatted{readLines("/tmp/err")
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#> [1] "hello again!"                                                              
</pre></div>
}}


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

}

\subsection{Background R processes}{

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

\if{html}{\out{<div class="sourceCode r">}}\preformatted{rp <- callr::r_bg(function() Sys.sleep(.2))
rp
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#> PROCESS 'R', running, pid 93508.                                                
</pre></div>
}}


This is a list of all \code{r_process} methods:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{ls(rp)
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#>  [1] "as_ps_handle"          "clone"                 "finalize"                 
#>  [4] "format"                "get_cmdline"           "get_cpu_times"            
#>  [7] "get_error_connection"  "get_error_file"        "get_exe"                  
#> [10] "get_exit_status"       "get_input_connection"  "get_input_file"           
#> [13] "get_memory_info"       "get_name"              "get_output_connection"    
#> [16] "get_output_file"       "get_pid"               "get_poll_connection"      
#> [19] "get_result"            "get_start_time"        "get_status"               
#> [22] "get_username"          "get_wd"                "has_error_connection"     
#> [25] "has_input_connection"  "has_output_connection" "has_poll_connection"      
#> [28] "initialize"            "interrupt"             "is_alive"                 
#> [31] "is_incomplete_error"   "is_incomplete_output"  "is_supervised"            
#> [34] "kill"                  "kill_tree"             "poll_io"                  
#> [37] "print"                 "read_all_error"        "read_all_error_lines"     
#> [40] "read_all_output"       "read_all_output_lines" "read_error"               
#> [43] "read_error_lines"      "read_output"           "read_output_lines"        
#> [46] "resume"                "signal"                "supervise"                
#> [49] "suspend"               "wait"                  "write_input"              
</pre></div>
}}


These include all methods of the \code{processx::process} superclass and the new \code{get_result()} method, to retrieve the R object returned by the function call.
Some of the handiest methods are:
\itemize{
\item \code{get_exit_status()} to query the exit status of a finished process.
\item \code{get_result()} to collect the return value of the R function call.
\item \code{interrupt()} to send an interrupt to the process. This is equivalent to a \code{CTRL+C} key press, and the R process might ignore it.
\item \code{is_alive()} to check if the process is alive.
\item \code{kill()} to terminate the process.
\item \code{poll_io()} to wait for any standard output, standard error, or the completion of the process, with a timeout.
\item \verb{read_*()} to read the standard output or error.
\item \code{suspend()} and \code{resume()} to stop and continue a process.
\item \code{wait()} to wait for the completion of the process, with a timeout.
}
}

\subsection{Multiple background R processes and \code{poll()}}{

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

\if{html}{\out{<div class="sourceCode r">}}\preformatted{rp1 <- callr::r_bg(function() \{ Sys.sleep(1/2); "1 done" \})
rp2 <- callr::r_bg(function() \{ Sys.sleep(1/1000); "2 done" \})
processx::poll(list(rp1, rp2), 1000)
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#> [[1]]                                                                           
#>   output    error  process                                                      
#> "silent" "silent" "silent"                                                      
#>                                                                                 
#> [[2]]                                                                           
#>  output   error process                                                         
#> "ready" "ready" "ready"                                                         
#>                                                                                 
</pre></div>
}}


\if{html}{\out{<div class="sourceCode r">}}\preformatted{rp2$get_result()
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#> [1] "2 done"                                                                    
</pre></div>
}}


\if{html}{\out{<div class="sourceCode r">}}\preformatted{processx::poll(list(rp1), 1000)
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#> [[1]]                                                                           
#>  output   error process                                                         
#> "ready" "ready" "ready"                                                         
#>                                                                                 
</pre></div>
}}


\if{html}{\out{<div class="sourceCode r">}}\preformatted{rp1$get_result()
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#> [1] "1 done"                                                                    
</pre></div>
}}

}

\subsection{Persistent R sessions}{

\code{r_session} is another \code{processx::process} subclass that represents a persistent background R session:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{rs <- callr::r_session$new()
rs
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#> R SESSION, alive, idle, pid 93547.                                              
</pre></div>
}}


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

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

\if{html}{\out{<div class="sourceCode r">}}\preformatted{rs <- callr::r_session$new()
rs$run(function() runif(10))
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#>  [1] 0.9610059 0.1697476 0.4644942 0.7274561 0.5235966 0.2661597 0.6214701      
#>  [8] 0.9156920 0.5577677 0.8844519                                              
</pre></div>
}}


\if{html}{\out{<div class="sourceCode r">}}\preformatted{rs$call(function() rnorm(10))
rs
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#> R SESSION, alive, busy, pid 93551.                                              
</pre></div>
}}


\if{html}{\out{<div class="sourceCode r">}}\preformatted{rs$poll_process(2000)
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#> [1] "ready"                                                                     
</pre></div>
}}


\if{html}{\out{<div class="sourceCode r">}}\preformatted{rs$read()
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#> $code                                                                           
#> [1] 200                                                                         
#>                                                                                 
#> $message                                                                        
#> [1] "done callr-rs-result-16cf57f352725"                                        
#>                                                                                 
#> $result                                                                         
#>  [1]  0.6357407  0.3347589  1.1821022  1.1821849  1.8102056 -0.6755208          
#>  [7] -0.7085879  1.3591706  0.8677449 -0.5669537                                
#>                                                                                 
#> $stdout                                                                         
#> [1] ""                                                                          
#>                                                                                 
#> $stderr                                                                         
#> [1] ""                                                                          
#>                                                                                 
#> $error                                                                          
#> NULL                                                                            
#>                                                                                 
#> attr(,"class")                                                                  
#> [1] "callr_session_result"                                                      
</pre></div>
}}

}

\subsection{Running \verb{R CMD} commands}{

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

\if{html}{\out{<div class="sourceCode r">}}\preformatted{callr::rcmd("config", "CC")
}\if{html}{\out{</div>}}\if{html}{\out{
<div class="asciicast" style="color: #B9C0CB;font-family: 'Fira Code',Monaco,Consolas,Menlo,'Bitstream Vera Sans Mono','Powerline Symbols',monospace;line-height: 1.300000"><pre>
#> $status                                                                         
#> [1] 0                                                                           
#>                                                                                 
#> $stdout                                                                         
#> [1] "clang -arch arm64 -std=gnu2x\\n"                                            
#>                                                                                 
#> $stderr                                                                         
#> [1] ""                                                                          
#>                                                                                 
#> $timeout                                                                        
#> [1] FALSE                                                                       
#>                                                                                 
#> $command                                                                        
#> [1] "/Library/Frameworks/R.framework/Versions/4.5-arm64/Resources/bin/R"        
#> [2] "CMD"                                                                       
#> [3] "config"                                                                    
#> [4] "CC"                                                                        
#>                                                                                 
</pre></div>
}}


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

\subsection{Observability}{

callr is instrumented with \href{https://opentelemetry.io/}{OpenTelemetry}.
When an OpenTelemetry SDK (such as \href{https://otelsdk.r-lib.org}{otelsdk}) is loaded and configured, callr emits spans for every R subprocess it starts and propagates the W3C \code{traceparent} header into the subprocess, so spans created inside the child become children of the parent span.
No code changes are needed in callr-using code — the existing entry points start emitting telemetry as soon as an SDK is configured.

See \code{vignette("opentelemetry", package = "callr")} for what callr emits, how subprocess context propagation works, and how to test your own instrumentation on top of it.
}

\subsection{Configuration}{
\subsection{Environment variables}{
\itemize{
\item \code{CALLR_NO_TEMP_DLLS}: If \code{true}, then callr does not use a temporary
directory to copy the client DLL files from, in the subprocess. By
default callr copies the DLL file that drives the callr subprocess into
a temporary directory and loads it from there. This is mainly to avoid
locking a DLL file in the package library, on Windows. If this default
causes issues for you, set it to \code{true}, and then callr will use the DLL
file from the installed processx package. See also
https://github.com/r-lib/callr/issues/273.
\item \code{CALLR_TMPDIR}: If set to a non-empty path, callr writes its auxiliary
temporary files into this directory instead of the session's \code{tempdir()}.
The directory is created if it does not exist. The value is read on each
use, so it can be changed at run time via \code{Sys.setenv()}. Note that paths
cached at package load time (the package's own \verb{callr-env-} file and the
client DLL location) only honor this setting if the variable was set
before \code{callr} was loaded, typically by exporting it in the shell or via
\code{.Renviron}. See also https://github.com/r-lib/callr/issues/172.
}
}

}

\subsection{Code of Conduct}{

Please note that the callr project is released with a
\href{https://callr.r-lib.org/CODE_OF_CONDUCT.html}{Contributor Code of Conduct}.
By contributing to this project, you agree to abide by its terms.
}
}

\seealso{
Useful links:
\itemize{
  \item \url{https://callr.r-lib.org}
  \item \url{https://github.com/r-lib/callr}
  \item Report bugs at \url{https://github.com/r-lib/callr/issues}
}

}
\author{
\strong{Maintainer}: Gábor Csárdi \email{csardi.gabor@gmail.com} (\href{https://orcid.org/0000-0001-7098-9676}{ORCID}) [copyright holder]

Authors:
\itemize{
  \item Gábor Csárdi \email{csardi.gabor@gmail.com} (\href{https://orcid.org/0000-0001-7098-9676}{ORCID}) [copyright holder]
  \item Winston Chang
}

Other contributors:
\itemize{
  \item Posit Software, PBC (\href{https://ror.org/03wc8by49}{ROR}) [copyright holder, funder]
  \item Ascent Digital Services [copyright holder, funder]
}

}
\keyword{internal}
