在脚本中,我经常调用函数Rcplex(),它将“CPLEX环境打开”和“已关闭的CPLEX环境”打印到控制台.由于该函数被频繁调用,因此它经常打印,这非常烦人.有没有办法压制这个?我尝试了sink(),suppressWarnings / Messages或者invisible(catch.output()),但这些都没有.我继续检查Rcplex()的代码,并找到打印到控制台的位置. Rcplex()调用底层C函数(Rcplex.c).在
code of rcplex.c中,我找到了导致打印的命令:
REprintf("CPLEX environment opened\n"); REprintf("Closed CPLEX environment\n");
有没有办法从REprintf()捕获输出,以便它不会打印到R控制台?显然,一种方法是乱用Rcplex.c文件并删除相应的行.但是,这不是一个非常干净的解决方案,这就是为什么我要求另一种方法来捕获C函数的输出.
解决方法
您通常使用sink()和capture.output()时遇到问题,因为sink()不会重定向REprintf的输出,正如我们在
source code中对REprintf的注释中所看到的:
/* ========= * Printing: * ========= * * All printing in R is done via the functions Rprintf and REprintf * or their (v) versions Rvprintf and REvprintf. * These routines work exactly like (v)printf(3). Rprintf writes to * ``standard output''. It is redirected by the sink() function,* and is suitable for ordinary output. REprintf writes to * ``standard error'' and is useful for error messages and warnings. * It is not redirected by sink().
但是,我们可以使用type =“message”来处理这个问题;来自help(“capture.output”):
Messages sent to stderr() (including those from message,warning and
stop) are captured by type = “message”. Note that this can be “unsafe” and should only be used with care.
首先,我使用您正在处理的相同行为创建一个C函数:
#include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] NumericVector example_function(NumericVector x) { REprintf("CPLEX environment opened\n"); REprintf("Closed CPLEX environment\n"); // As mentioned by Dirk Eddelbuettel in the comments,// Rcpp::Rcerr goes into the same REprintf() stream: Rcerr << "Some more stuff\n"; return x; }
如果我通常从R调用它,我得到:
example_function(42) CPLEX environment opened Closed CPLEX environment Some more stuff [1] 42
但是,我可以这样做:
invisible(capture.output(example_function(42),type = "message")) [1] 42
虽然输出打印到控制台,但消息却没有.
警告
如果我没有提到上面引用的帮助文件中的警告,我会失职:
Note that this can be “unsafe” and should only be used with care.
> log("A") Error in log("A") : non-numeric argument to mathematical function > invisible(capture.output(log("A"),type = "message")) >
因此,您可能希望或不希望将捕获的输出发送到文本文件,以防您必须诊断出错的地方.例如:
invisible(capture.output(log("A"),type = "message",file = "example.txt"))
然后我不必在控制台中看到消息,但如果我之后需要检查example.txt,那么消息就在那里:
Error in log("A") : non-numeric argument to mathematical function