您尚未提供您的 compile() 函数,但我假设它运行一个调用 g++ 来编译 Mymodel.cpp 的系统命令。
在这种情况下,g++ 进程会将其错误输出打印到 stderr。使用 R 捕获此输出的唯一方法是使用 stderr=T 调用 system2()。请注意,system() 不具备直接捕获 stderr 的能力(尽管它可以通过 intern=T 捕获 stdout,并且您可以将 2>&1 添加到 shell 命令中以捕获 stderr,因此这是另一个可行的选择)。 sink() 不捕获系统命令输出;它只捕获 R 输出。
我建议将您的compile() 函数中的可变参数传递给system2() 调用,从而参数化您对compile() 的调用是否导致g++ 的stderr 进入终端或@ 的返回值987654339@ 功能。这是如何完成的:
write('error!','test1.cpp'); ## generate a test file with invalid C++
compile <- function(file,...) system2('g++',file,...);
compile('test1.cpp'); ## output lost to the terminal
## test1.cpp:1:1: error: ‘error’ does not name a type
## error!
## ^
output <- compile('test1.cpp',stdout=T,stderr=T); ## capture output
## Warning message:
## running command ''g++' 'test1.cpp' 2>&1' had status 1
output;
## [1] "test1.cpp:1:1: error: ‘error’ does not name a type"
## [2] " error!"
## [3] " ^"
## attr(,"status")
## [1] 1
write(output,'output.txt'); ## write output to a text file
cat(readLines('output.txt'),sep='\n'); ## show it
## test1.cpp:1:1: error: ‘error’ does not name a type
## error!
## ^
如果您真的想捕获compile() 函数中生成的所有 输出,则可以将上述解决方案与sink() 结合使用,如下所示:How to save all console output to file in R?。
在这种情况下,我建议放弃可变参数的想法,并为compile() 添加一个附加参数,它将采用一个输出文件名,所有输出都将写入其中。
这将需要对附加参数缺失的几个预测:
write('error!','test1.cpp'); ## generate a test file with invalid C++
compile <- function(file,outputFile) {
if (!missing(outputFile)) {
outputCon <- file(outputFile,'wt'); ## require file name
sink(outputCon);
sink(outputCon,type='message'); ## must sink messages separately
warn.old <- options(warn=1)$warn; ## necessary to capture warnings as they occur
}; ## end if
cat('some random output 1\n');
if (!missing(outputFile)) {
output <- system2('g++',file,stdout=T,stderr=T); ## before flush to get warnings
sink(); ## force flush before appending system command output
sink(type='message');
outputCon <- file(outputFile,'at'); ## must reopen connection for appending
write(output,outputCon);
sink(outputCon);
sink(outputCon,type='message');
} else {
system2('g++',file);
}; ## end if
cat('some random output 2\n');
if (!missing(outputFile)) {
sink();
sink(type='message');
options(warn=warn.old);
}; ## end if
}; ## end compile()
compile('test1.cpp'); ## output lost to the terminal
## some random output 1
## test1.cpp:1:1: error: ‘error’ does not name a type
## error!
## ^
## some random output 2
compile('test1.cpp','output.txt'); ## internally capture all output
cat(readLines('output.txt'),sep='\n'); ## show it
## some random output 1
## Warning: running command ''g++' test1.cpp 2>&1' had status 1
## test1.cpp:1:1: error: ‘error’ does not name a type
## error!
## ^
## some random output 2