I'd like to suppress messages from R in rpy2 and thought the following would be enough:
>>> from rpy2.robjects.packages import importr
>>> import rpy2.robjects as robjs
>>> suppmsg = robjs.r["suppressMessages"]
but then I get:
>>> suppmsg(robjs.r.message("hello"))
R[write to console]: hello
I don't mind the messages during interactive work, but I want them off in a library. How can they be turned off?
Your code might not do what you expect to because in R the evaluation of expressions is lazy and in Python it is not.
For example, when doing in R
suppressMessages(library("foo"))
what happens is that the function suppressMessages()
is called with the unevaluated expression library("foo")
as an argument. In the body of the function suppressMessages()
code that turns off the display of messages globally is first run, and then the expression is evaluated, and finally code that restores the display of messages is run.
In Python, doing
suppmsg(robjs.r.message("hello"))
will first evaluate robjs.r.message("hello")
(which calls the R function function message()
through rpy2
) and the result of this evaluation (what is returned by the function) is passed as an argument to suppmsg()
.
If you only want to silence import of a library, the function rpy2.robjects.packages.quiet_require()
can do that for you.